【问题标题】:I write to a file but the changes doesn't save我写入文件但更改未保存
【发布时间】: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 standard7.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


【解决方案1】:

当使用+ 模式打开文件并在读取之后写入时,必须在调用文件定位函数之前。

从文件中读取一些字符后,您需要调用:fseek, fsetpos 或倒带功能。

要修复代码,请存储您从该文件中读取的总字符数,然后调用函数 fseek,其中第二个参数是计数,第三个参数是 SEEK_SET。

【讨论】:

  • 但是 fgetc() 不会将“seek”移动到下一个字符吗?
  • @GuyShilman 这无关紧要,如果您在+ 中打开,则需要这样做。
  • charCount = ftell(file); fseek(file, charCount, SEEK_SET);
  • 我添加了这个,现在它可以完美运行了!谢谢@2501
猜你喜欢
  • 2021-09-24
  • 2021-01-20
  • 1970-01-01
  • 2020-08-08
  • 2018-01-10
  • 1970-01-01
  • 2020-12-08
  • 2021-06-12
  • 1970-01-01
相关资源
最近更新 更多