一个线程只写,一个线程只读时,最好不要用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;
}