c - 从多个线程写入不同文件后获取ferror()

标签 c file file-io

我试图生成多个线程,并为每个线程写入不同的文件(线程 1 写入文件 1,等等...)。但是,在设置线程执行 Ferror() 后,我无法在主进程中执行进一步的文件操作。我尝试清除错误,但没有解决。这是我目前拥有的代码:

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

void * bla (void *arg) {
    fprintf((FILE *) arg, "Hey, printing to file");
}

int main() {
    FILE *f1 = fopen("out0", "rw");
    FILE *f2 = fopen("out1", "rw");

    pthread_t t[2];
    pthread_create(&t[0], NULL, bla, f1);
    pthread_create(&t[1], NULL, bla, f2);

    pthread_join(t[0], NULL);
    pthread_join(t[1], NULL);
    printf("%d\n", ferror(f2));   // ERROR: ferror() is set to 1 here!

    //fseek(f1, 0, SEEK_END);
    fseek(f2, 0, SEEK_END);
    long pos = ftell(f2);         // This still works
    printf("%ld\n", pos);
    clearerr(f2);                 // Trying to clear the error, flag clears, but further operations fail
    char *bytes = malloc(pos);
    int err = fread(bytes, 1, 4, f2);  // fread returns 0
    printf("%d\n", ferror(f2));
    printf("%d\n", err);
    bytes[pos-1] = '\0';
    printf("%s", bytes);
    free (bytes);

    fclose(f1);
    fclose(f2);

    return 0;

注意,线程打开的文件不应该存在,如果存在则应清除。 任何帮助将不胜感激。谢谢!

最佳答案

fopen

mode 参数应为 "r+"(如果文件应该存在)或 "w+" (或者甚至可能是"a+")而不是"rw"。字符串 "rw" 不是有效模式,可能会被解释为 "r" 模式,并且您不能 fprintf 来这样一个FILE*

关于c - 从多个线程写入不同文件后获取ferror(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14821552/

相关文章:

python - 如何创建索引来解析大文本文件

c++ - Windows CopyFileA 失败然后成功

oracle - 间歇性 ORA-22288 错误 - 命令长度不正确

c++ - 带有字符串文字的 C 空指针

c - 让用户输入名称但使用文件流 *fp

指向多个函数的 C 指针

c - 如何在不使用 C 中的 "dirent.h"(visual studio 2017 windows)的情况下查找特定目录中的所有文件名

java - 创建 FileReader 哪种方式更适合优化?

Java vs C# 多线程性能,为什么 Java 变慢了? (包括图表和完整代码)

c++ - typedef 中的三个术语是什么意思?