【发布时间】:2020-08-19 10:16:45
【问题描述】:
我想将数据从套接字读取到 FILE。如果 FILE 不存在,创建一个文件 ONLY 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, 0, SEEK_CUR);
}
size = ftell(fp);
}
// printf("Buffer = %s", buffer);
}
【问题讨论】:
-
使用
O_APPEND。那么你根本不需要文件指针。 -
使用
FILE *fp = fopen(filename, "a");而不是open。 -
@RobertoCaboni 然后丢掉
fdopen()... -
fd = open("/home/regs_p/cprograms/tcp/RSA.c", O_WRONLY | O_APPEND | O_CREAT | O_TRUNC);不完整。创建文件时,您需要向open()提供第三个mode_t参数,例如fd = open("/home/regs_p/cprograms/tcp/RSA.c", O_WRONLY | O_APPEND | O_CREAT | O_TRUNC, 0644); -
@Andrew Henle - 是的,对。我忘记了“Umask”值。大约 12 年前,在我的 Unix 和 Shell 脚本编程课程中了解了“Umask”。谢谢提醒!
标签: c file sockets flags file-descriptor