Open, read and write csv

Asked

Viewed 382 times

0

I have a C code that is using the base structure for reading.

Read

FILE *input;
input=fopen(argv[1],"r");
points=(Point*)malloc(sizeof(Point)*num_points);
readPoints(input,points,num_points);
fclose(input);

Record

FILE* output=fopen(argv[2],"w");
fprintf(output,"%d\n",num_clusters);
fprintf(output,"%d\n",num_points);
fclose(output);

My question is how I can read a csv file so that I don’t know how many lines it has and after that record the data in another csv file. It would be the same C procedure with EOF/! EOF and the code the way I did, or it will be done differently?

Thank you very much.

1 answer

0

The function int feof(FILE *), stated in stdio.h, returns 0 if the file still has bytes to read, and 1 if you have found the end of the file. With this, you can execute a loop and transcribe the CSV:

FILE * input, * output;
char buffer[2048];
input = fopen(argv[1], "r");
output = fopen(argv[2], "w");
while (! feof(input)) {
    fgets(buffer, sizeof(buffer), input);
    tratar(buffer); /* esta função vai executar algum tratamento arbitrário na linha */
    fputs(buffer, output);
}
fclose(input);
fclose(output);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.