用c语音写2个线程循环读写同一个文件没报错就不退出
时间: 2024-05-07 21:16:30 浏览: 12
您好,对于您的问题,我可以给出以下答案:
下面是一个用C语言编写的读写同一个文件的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define FILENAME "test.txt"
void *read_file(void *arg);
void *write_file(void *arg);
int main()
{
pthread_t read_thread, write_thread;
int rc;
rc = pthread_create(&read_thread, NULL, read_file, NULL);
if(rc != 0)
{
printf("创建读线程失败\n");
exit(1);
}
rc = pthread_create(&write_thread, NULL, write_file, NULL);
if(rc != 0)
{
printf("创建写线程失败\n");
exit(1);
}
pthread_join(read_thread, NULL);
pthread_join(write_thread, NULL);
return 0;
}
void *read_file(void *arg)
{
FILE *fp = fopen(FILENAME, "r");
if(fp == NULL)
{
printf("无法打开文件\n");
exit(1);
}
char c;
while((c = getc(fp)) != EOF)
{
putchar(c);
}
fclose(fp);
return NULL;
}
void *write_file(void *arg)
{
FILE *fp = fopen(FILENAME, "a");
if(fp == NULL)
{
printf("无法打开文件\n");
exit(1);
}
while(1)
{
fputs("HELLO WORLD\n", fp);
fflush(fp);
}
fclose(fp);
return NULL;
}
```
当然,在实际使用中需要注意许多细节,如线程同步、互斥等问题。