问题描述
我想从套接字读取数据到 FILE 。如果 FILE 不存在,请创建文件 ONCE 和来自客户端的所有后续数据,找到 FILE POINTER 的当前位置并追加最后的数据。
// Server is 'Ready' to read data from the socket :
// fd - declared as **static int**,to enable it bet'n the function calls
fd = open("/home/regs_p/cprograms/tcp/RSA.c",O_WRONLY | O_APPEND | O_CREAT | O_Trunc);
if (fd < 0) {
printf("Some problem with the file!");
}
else {
while ((b = read(sockfd,buffer,sizeof(buffer) - 1)) > 0) {
if (fd > 0 ) {
fp = fdopen(fd,"a+");
fwrite(buffer,sizeof(buffer),1,fp);
// fseek(fp,SEEK_CUR);
}
size = ftell(fp);
}
// printf("Buffer = %s",buffer);
}
解决方法
仅将O_APPEND
与O_CREAT
一起使用才创建文件。如果存在,默认情况下将打开文件,并且文件指针将位于末尾。