I have this code here :
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
int main()
{
FILE *inFile, *outFile;
int i;
char buffer[1];
bool lastIsComma = false;
inFile = fopen("csv.txt","r");
outFile = fopen("output.txt","w");
while(!feof(inFile))
{
fscanf(inFile,"%c",&buffer);
i = atoi(buffer);
if((i!=0) || (*buffer == '0'))
{
fprintf(outFile,"%d",i);
lastIsComma = false;
}
else
{
if((lastIsComma) && (feof(inFile)))
{
fputc('0',outFile);
}
if((lastIsComma) && (!feof(inFile)))
{
fputc('0',outFile);
fputc(',',outFile);
}
if((!lastIsComma) && (feof(inFile)))
{
fputc(',',outFile);
fputc('0',outFile);
}
if((!lastIsComma) && (!feof(inFile)))
{
fputc(',',outFile);
}
lastIsComma = true;
}
}
fclose(inFile);
fclose(outFile);
return 0;
}
What this code does is to add zero between consecutive commas in a csv, for example, 1,2,,,,3, -> 1,2,0,0,0,3,0
My code works for csv ending with commas like the example above, but not for csv ending with values, like 1,2,3,4,5 ( I got 1,2,3,4,55 instead, with an extra '5' at the end).
Can anybody suggest what is wrong in the code?