C++多线程测试 文件读取过程有新内容

一个线程只写,一个线程只读时,最好不要用while来循环读取文件内容。
因为如果新内容的增加速度很快,那么就始终无法完成文件的读取。

#include <cstdio>
#include <thread>

void writeData() {
    FILE *fp = fopen("out.txt", "a");
    for (int i = 0; i < 10; ++i) {
        {
            char a[] = "Andy";
            char b[] = "body";
            char c[] = "city";
            printf("i=%d,a=%s,b=%s,c=%s\n", i, a, b, c);
            fprintf(fp, "i=%d,a=%s,b=%s,c=%s\n", i, a, b, c);
            fflush(fp);
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}
void readData() {
    FILE *fp = fopen("out.txt", "r");
    char s[1024];
    while (fgets(s, sizeof(s), fp) != NULL) {
        printf("read:%s", s);
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
    printf("end\n");
}

int main() {
    // 让读取先执行,然后等1秒后再启动写入线程
    // 读取时out.txt里只有2行数据 但随着写入线程的启动 他能读取到新追加的数据

    std::thread reader(readData);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::thread writer(writeData);

    std::this_thread::sleep_for(std::chrono::seconds(60));

    return 0;
}

不同的文件指针,其内部指针是独立的,互不影响。所以最好是用fread读取,当时获取到的文件大小有多大,就读取多大。

#include <cstdio>
#include <thread>

void writeData() {
    FILE *fw = fopen("out.txt", "a");
    for (int i = 0; i < 5; ++i) {
        fprintf(fw, "i=%d\n", i);
        fflush(fw);
        std::this_thread::sleep_for(std::chrono::milliseconds(800));
    }
}

void readData() {
    for (int i = 0; i < 5; ++i) {
        FILE *fp = fopen("out.txt", "rb");
        fseek(fp, 0, SEEK_END);
        size_t size = ftell(fp);
        fseek(fp, 0, SEEK_SET);
        char *s = new char[size + 1];
        fread(s, 1, size, fp);
        s[size] = '\0';
        printf("read:\n %s end\n", s);
        delete[] s;
        std::this_thread::sleep_for(std::chrono::milliseconds(800));
    }
}

int main() {
    std::thread reader2(readData);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::thread writer(writeData);

    std::this_thread::sleep_for(std::chrono::seconds(60));
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值