【发布时间】:2016-09-26 16:35:12
【问题描述】:
我正在编写一个函数来更改 csv 文件中的值,vs 调试器说它工作正常,但是在程序退出后,我在文件中看到没有进行任何更改。你知道为什么吗?
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;
}
【问题讨论】:
-
您没有检查来自
fputc()或fclose()的返回值。 -
如果文件能够打开,fclose() 必须工作,如果我在下一行,我只需要检查 fgetc() 并且在 csv 表的那一行
-
如果文件能够打开,fclose() 必须工作 这根本不是真的。根据C standard,7.21.5.1
fclose函数:成功调用fclose函数会导致stream指向的流和相关文件被刷新被关闭。流的任何未写入缓冲数据都将传递到主机环境以写入文件;任何未读的缓冲数据都将被丢弃。调用是否成功... 刷新缓冲区可能会失败。 -
函数:
fgetc()返回一个int,而不是char,(并且不能使用char对EOF 进行可靠性检查。所以这一行:char letter = ' ';应该是:@ 987654333@ 始终在启用所有警告的情况下进行编译,然后修复这些警告。 -
函数:
strlen()返回一个size_t(无符号长整数),因此变量i应声明为size_t而不是int
标签: c file csv writetofile