Adds better file error handling
Creates a find id function
This commit is contained in:
parent
f1a6af2d35
commit
4d3dfee74c
38
src/csv.c
38
src/csv.c
@ -9,7 +9,7 @@
|
|||||||
#include "json.h"
|
#include "json.h"
|
||||||
#include "csv.h"
|
#include "csv.h"
|
||||||
|
|
||||||
#define MAX_BUFFER_SIZE 512
|
#define MAX_BUFFER_SIZE 1024
|
||||||
|
|
||||||
int get_next_id()
|
int get_next_id()
|
||||||
{
|
{
|
||||||
@ -31,6 +31,37 @@ int get_next_id()
|
|||||||
return atoi(id) + 1;
|
return atoi(id) + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
long find_id(int id_to_find)
|
||||||
|
{
|
||||||
|
FILE* csv;
|
||||||
|
char* buffer;
|
||||||
|
size_t line_size = MAX_BUFFER_SIZE - 1;
|
||||||
|
int i, file_exists;
|
||||||
|
long file_pos;
|
||||||
|
|
||||||
|
|
||||||
|
file_exists = access(FILE_NAME, F_OK);
|
||||||
|
if (0 != file_exists) {
|
||||||
|
fprintf(stderr, "%s does not exist!", FILE_NAME);
|
||||||
|
exit(EXIT_FAILURE);
|
||||||
|
}
|
||||||
|
|
||||||
|
csv = fopen(FILE_NAME, "r");
|
||||||
|
if (NULL == csv) {
|
||||||
|
fprintf(stderr, "Failed to open %s!\n", FILE_NAME);
|
||||||
|
exit(EXIT_FAILURE);
|
||||||
|
}
|
||||||
|
|
||||||
|
for(i = 0; i < id_to_find + 1; i++)
|
||||||
|
getline(&buffer, &line_size, csv);
|
||||||
|
|
||||||
|
file_pos = ftell(csv);
|
||||||
|
fclose(csv);
|
||||||
|
|
||||||
|
return file_pos;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
void write_to_file(book_t* book)
|
void write_to_file(book_t* book)
|
||||||
{
|
{
|
||||||
FILE* file;
|
FILE* file;
|
||||||
@ -52,6 +83,11 @@ void write_to_file(book_t* book)
|
|||||||
book_id = get_next_id();
|
book_id = get_next_id();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (NULL == file) {
|
||||||
|
fprintf(stderr, "Failed to open %s!\n", FILE_NAME);
|
||||||
|
exit(EXIT_FAILURE);
|
||||||
|
}
|
||||||
|
|
||||||
// now we write the information
|
// now we write the information
|
||||||
fprintf(file, "%d,\"%s\",\"%s\",\"%s\",\"%s\",%d,%d\n",
|
fprintf(file, "%d,\"%s\",\"%s\",\"%s\",\"%s\",%d,%d\n",
|
||||||
book_id, book->isbn, book->title, book->authors, book->image_url, book->year_of_publication, book->page_len);
|
book_id, book->isbn, book->title, book->authors, book->image_url, book->year_of_publication, book->page_len);
|
||||||
|
@ -7,4 +7,6 @@ int get_next_id();
|
|||||||
|
|
||||||
void write_to_file(book_t* book);
|
void write_to_file(book_t* book);
|
||||||
|
|
||||||
|
long find_id(int id_to_find);
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
@ -80,6 +80,8 @@ void process_args(char* argv[])
|
|||||||
|
|
||||||
int main(int argc, char* argv[])
|
int main(int argc, char* argv[])
|
||||||
{
|
{
|
||||||
|
return 0;
|
||||||
|
|
||||||
if (1 == argc) {
|
if (1 == argc) {
|
||||||
printf("Not enough arguments! Try typing %s --help\n", argv[0]);
|
printf("Not enough arguments! Try typing %s --help\n", argv[0]);
|
||||||
return EXIT_FAILURE;
|
return EXIT_FAILURE;
|
||||||
|
Loading…
x
Reference in New Issue
Block a user