所以我正在尝试将数据从原始文件更新到新的临时文件,然后我删除原始文件并使用原始文件的名称重命名临时文件,如下所示:
#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.
您根本不需要打开和/或关闭文件。如果您看到 remove
和 rename
完全没有使用前一部分代码。还要检查 man rename
和 man remove
。如果您想知道文件是否存在。检查这些函数的返回值。如果出现错误,您始终可以检查 errno
以了解到底出了什么问题。 (有关详细信息,请参阅联机帮助页)。
关于c - 删除和重命名文件时出现 C 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50436403/