【发布时间】:2015-03-16 09:38:30
【问题描述】:
一个小前提:服务器正在通过套接字接收消息“get text.txt” 我必须计算该文件的大小并将其发回,所以这是到目前为止的代码:
/*Receive command
*
*/
char * file_path;
//Wait for command
if ( recvfrom (sockfd_child, command, PACKET_SIZE, 0, (struct sockaddr *) addr_client, &addr_client_lenght) < 0) {
perror("server: error in recvfrom for command packet");
exit(1);
}
//check first 4 character (COMMAND_SIZE) of command packet send by the client to identify the operation
if (!strncmp(command, "get ", COMMAND_SIZE)) {
file_path = malloc(sizeof(command)-COMMAND_SIZE);
strcpy(file_path, DIRECTORY);
strncat(file_path, command+COMMAND_SIZE, PACKET_SIZE-COMMAND_SIZE);
printf("Getting file in path: '%s'\n", file_path);
int file_size = get_file_size(file_path);
计算file_size的函数是
long get_file_size(char * file_name) {
long size;
FILE * file;
if ( !( file = fopen ( file_name , "rb" ) ) ) {
perror("file: error calculating size");
exit (1);
}
fseek (file , 0 , SEEK_END);
size = ftell (file);
rewind (file);
fclose(file);
return size;
}
DIRECTORY 是一个常量,设置为 ./files/
COMMAND_SIZE 设置为 4
程序的网络部分运行良好,命令字符串传输成功。
程序在错误打印file: error calculating size: No such file or directory 时停止在函数中,但前面的 printf 打印文件所在的当前路径Getting file in path: './files/text.txt'
所以我猜错误在于我如何将文件路径与命令“get”或我无法掌握的其他地方分开。你能帮助我吗?抱歉有任何错误或困惑,但现在是凌晨 4:00 :)
【问题讨论】:
-
请做一个可以被其他人测试的例子,也请看这里的说明。stackoverflow.com/tags/c/info
-
大胆猜测,因为您使用的是相对路径:服务器进程的工作目录可能不是您认为的那样。使用
getcwd获取并打印当前工作目录;./files/test.txt相对于该目录是否存在? -
在计算文件大小时,请考虑函数
fsetpos()和fgetpos()。其中使用的整数是操作系统的正确大小。long,fseek()和ftell()使用的可能不够用。 -
@Wintermute 原来你是对的,我检查了工作目录,发现我把文件目录放在它的子目录(\Release)中,这是可执行文件所在的位置,我想是正确的。
标签: c file network-programming