#include <QCoreApplication>
#include <stdio.h>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int x = 2;
FILE *fp [x];
fp[0] = fopen ("temp.txt", "w");
fp[1] = fopen ("temp.txt", "w");
if (fp[1])
qDebug () << "Fine";
fputs ("What is your name?\n", fp[0]);
fputs ("What is your name?\n", fp[0]);
fputs ("What is your name?\n", fp[0]);
fputs ("My name is XYZ.\n", fp[1]);
fputs ("What is your name?\n", fp[0]);
fputs ("What is your name?\n", fp[0]);
fclose (*fp);
return a.exec();
}
为了方便起见,我使用 Qt。
正在打印“Fine”字样。
这个程序的输出是:
What is your name?
What is your name?
What is your name?
What is your name?
What is your name?
为什么输出中缺少 My name is XYZ.
?如何使这些文件指针顺序写入一个文件?
最佳答案
借自Opening a file using fopen with same flag in C
You have 2
FILE*
open to the same file, pointing at the beginning of the file, so one of the writes overwrites the other.Note also that FILE* are normally buffered, so these small strings actually gets written to the file when you fclose() or fflush() the FILE*. Since you do neither, the system will do it when the application exits , so which write gets overwritten depends on which file the system closes first.
If you open the 2 files in append mode , fopen("mytext","a");, you'll see different result, but you'll need to fflush() the FILE* when you want to make sure operating on the other FILE* doesn't cause interleaved output. And writing to the same file from different processes/threads will take more care, e.g. some form of file locking.
在您的情况下,您要关闭 fp[0]
而不是 fp[1]
。两次写入都是独立的,可能 "My name is XYZ.\n"
首先被刷新到文件中(到开头),然后是所有字符串 "What is your name?\n"
从头开始刷新到文件中,覆盖上一行。
How to make 2 file pointers write in one file sequentially in C++?
不要使用 fopen
重新打开文件并使用相同的文件描述符或使用日志实用程序函数,该函数保留指向打开文件的静态指针或在每次登录并关闭文件时打开文件日志记录。
static void log(char *line)
{
static FILE *fp = fopen("temp.txt", "w");
if(fp) fputs ("What is your name?\n", fp);
}
然后在 main() 中
log("What is your name\n");
关于c++ - 如何在 C++ 中使 2 个文件指针顺序写入一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35932332/