Linux IO chatter

本文提供了一个简单的文件通信程序示例,展示了如何通过读写特定文件来进行消息传递。程序包括两个部分:一方负责从文件中读取消息并显示,另一方则负责向文件中写入消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>   
#include <sys/types.h>  
#include <sys/stat.h>  
#include <errno.h>  
#include <string.h> 
/*


struct user{
    char name[10];
//    int num;
//    int age;
    char msg_send[80];
char msg_recv[80];
}boya,boyb,*pp,*qq;
*/
int main(void){
    int fp1,fp2;
char name_a[20],name_b[20] ;
char buf_recv[30];
char buf_send[30];
//  char ch;
   // int i;
int m,n;
 //   pp=boya;
  //  qq=boyb;
    


    printf("\n please input your name and your friend name \n");
scanf("%s %s",name_a,name_b) ;
//printf("your name is %s", boya->name");
while(1)
{
//open the file recv_b
if((fp1=open("note_recv_b.txt",O_RDWR|O_CREAT|O_APPEND))== 0){
        printf("Cannot open file note_recv_a any key exit!");
        getchar();
        exit(1);
}

//if new message comes


//read message from B
m = read(fp1,buf_recv,sizeof(buf_recv));//read from file note_recv_b
//
if(m > 0)
{
//print message from B
printf("hello %s,your get message from %s: \n ",name_a,name_b) ;
// print message on screen
write(STDOUT_FILENO,buf_recv,m);//print to screen
close(fp1);
}
else
{
if((fp2=open("note_recv_a.txt",O_RDWR|O_CREAT|O_APPEND))== 0){
printf("Cannot open file note_recv_a any key exit!");
getchar();
exit(1);
}
printf("\n you can send message to your friend %s :\n",name_b);
scanf("%s\n",buf_send);
//n = read(STDIN_FILENO,buf_send,30);//read send msg 
//move fp2 back 30 offset
// lseek(fp2,30,SEEK_SET);
write(fp2,buf_send,sizeof(buf_send));//write to note_recv_a
//close file
printf("you have send message to B:%s \n",buf_send);
//fclose(fp2);

  close(fp2);

}
//move fp to the end of file
//lseek(fp1,30, SEEK_SET);



//close file
//close(fp1) ;
//open note_recv_a to send message to B




}



/*
    for(i=0;i<1;i++,pp++)
        scanf("%s %s",boya->name,boya->,);
    pp=boya;
    fwrite(pp,sizeof(struct user),2,fp);
    rewind(fp);
    fread(qq,sizeof(struct user),2,fp);
    printf("\n\nname\tnumber      age      addr\n");
    for(i=0;i<2;i++,qq++)
printf("%s\t%5d%7d     %s\n",qq->name,qq->num,qq->age,qq->addr);
    fclose(fp);
*/
return 0 ;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值