c - 删除和重命名文件时出现 C 错误

标签 c file text

所以我正在尝试将数据从原始文件更新到新的临时文件,然后我删除原始文件并使用原始文件的名称重命名临时文件,如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(){
 FILE * fptr = NULL;
 FILE * temp;

    fptr = fopen("Original.txt", "rw+");
    temp = fopen("temp.txt", "w");

    if(fptr==NULL)//Check if file was opened successfully
    {
        printf("File could not be opened");
    }


    //cicle of me adding data to temp file

    fclose(fptr);
    fclose(temp);

    remove("Original.txt");
    rename("temp.txt","Original.txt");

    return 0;
    }

它第一次工作,但当我再次执行时,Original.txt 最终变成空白。是什么原因造成的?

我试过改变 temp = fopen("temp.txt", "w"); to temp = fopen("temp.txt", "ab+");但 Original.txt 的信息最终没有空格或换行符(全部在一起)。与“wb”相同

“rb”Original.txt 文件消失。

如有必要,我会添加整个代码,尽管我认为它不相关

最佳答案

当您执行 fopen (path, "w") 时,它会截断 path 指向的文件。然后关闭文件。因此,本质上,您的“temp.txt”是 fclose (temp) 行之后的一个空文件。去掉“w+”和“w”,因为它们会截断文件(使其长度为零)。

参见man fopen

w Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.

w+ Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.

您根本不需要打开和/或关闭文件。如果您看到 removerename 完全没有使用前一部分代码。还要检查 man renameman remove。如果您想知道文件是否存在。检查这些函数的返回值。如果出现错误,您始终可以检查 errno 以了解到底出了什么问题。 (有关详细信息,请参阅联机帮助页)。

关于c - 删除和重命名文件时出现 C 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50436403/

相关文章:

c - 为什么 *(str+i) = *(str +j) 在这里不起作用?

C++ 以<输入文件和>输出文件启动程序

c++ - 尝试读取二进制文件会清除文件本身

html - 显示多个等长的文本行

c - 找到程序中分配的内存?

c:当 1 维未知时 3d 数组的动态分配

c - void 指针发出警告正常吗?

Python 写入缓冲区而不是文件

java - 在 Java 中获取双字母组和三字母组的最简单方法或最轻量级的库?

c++ - 使用 winapi 的可变字体/格式的文本换行 block