I'm writing a function to change a value in a csv file, and the vs debugger says it's working perfectly, but after the program exits, I see in the file that no changes have been made. Do you know why?
int changeValue(int line, int row, char* text, char* fi_le)
/*line and row are the places in which the value is in the file and fi_le is
an address to the file*/
{
int i = 1;
char letter = ' ';
FILE* file = fopen(fi_le, "r+");
if (!(file))//checks that the file exists
{
printf("file r+ open in changeValue -- ERROR!");
return 1;
}
while (i < line)//first line is number 1
{
letter = fgetc(file);
if (letter == '\n')
{
i++;
}
}
i = 0;
while (i < row)//first row is number 0
{
letter = fgetc(file);
if (letter == ',')
{
i++;
}
}
for (i = 0; i < strlen(text) - 1; i++)//writes the new value in the old's value place
{
fputc(text[i], file);
}
fclose(file);
return 0;
}
When the file is open using the +
mode, and writes following reads, must be preceded by a call to a file positioning function.
After you read some characters from the file, you need to call either: fseek, fsetpos, or rewind, functions.
To fix the code, store the total character count you read in from this file, and then call function fseek, where the second argument is the count and the third is SEEK_SET.