我目前使用fwrite()将char[]缓冲区的内容写入文本文件。
这个链接的文档显示size_t是需要的,但是一个整数会有区别吗?我的输出文件显示为空白。
作为参考,这里是我的一个片段:
char* output_file;
int buffer_size = 20;
int sockfd = 0;
int bitsReceived = 0;
int totalBitsReceived = 0;
char recvBuffer[buffer_size];
struct sockaddr_in serv_addr, client_addr;
socklen_t alen = sizeof(serv_addr);
memset(recvBuffer, '0', sizeof(recvBuffer));
memset((char *)&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(server_port);
serv_addr.sin_addr.s_addr = inet_addr(server_ip);
if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
perror("Cannot create socket");
return 0;
}
/* Open the input file to read */
FILE *fp;
fp = fopen(input_file, "r");
size_t nread;
if (fp == NULL) {
perror("Error: ");
return(-1);
}
FILE *outputFilep;
outputFilep = fopen(output_file, "w");
bzero(recvBuffer, buffer_size);
/* Read input from server and write it to output file */
while((bitsReceived = recvfrom(sockfd, recvBuffer, buffer_size, 0, (struct sockaddr *)&serv_addr, &alen)) > 0) {
totalBitsReceived += bitsReceived;
size_t m = fwrite(recvBuffer, sizeof(char), (size_t)bitsReceived, outputFilep);
if (m < 0) {
perror("Error: ");
}
}
它不会,你可以使用int
-只要你确定它永远不会是负的,因为这将是一个问题。
负的-1
值可以作为错误指示返回。所以你必须在调用recvfrom()
后检查它。