c++ - 如何在 C++ 中使 2 个文件指针顺序写入一个文件?

标签 c++ file

#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/

上一篇:c++ - 限制上课

下一篇:c++ - 模板/多态性

相关文章:

c++ - 为什么将未使用的返回值强制转换为 void?

C++危险的类型转换代码

c++ - Break 关键字是退出 for 循环的最有效方法吗? C/C++

c - 如何使用文件结构?

c++ - 将自定义库链接到 C++ 中的现有程序

c++ - 菱形继承(钻石问题) - 从抽象类和具体类继承而不是实现基于共享的类

java - 尝试用另一种方法要求用户输入

python - 我应该使用哪种方法来访问文件,为什么?

javascript - 是否可以用 Blob 替换文件输入?

angular - 从 ngx-image-cropper 返回文件以上传 - Angular