Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 从字符串中的文件路径计算文件大小_C_File_Network Programming - Fatal编程技术网

C 从字符串中的文件路径计算文件大小

C 从字符串中的文件路径计算文件大小,c,file,network-programming,C,File,Network Programming,一个小前提:服务器通过套接字接收消息“gettext.txt” 我必须计算该文件的大小并将其发送回,因此,这里是到目前为止的代码: /*Receive command * */ char * file_path; //Wait for command if ( recvfrom (sockfd_child

一个小前提:服务器通过套接字接收消息“gettext.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);
目录是一个常量,设置为./files/
命令大小设置为4
程序的网络部分工作正常,命令字符串成功传输
程序在perror printing
file:计算大小时出错:没有这样的文件或目录
,但之前的printf打印文件所在的当前路径。
获取路径中的文件:'./files/text.txt'


因此,我猜错误在于我如何将文件路径与命令“get”或其他我无法理解的地方分开。你能帮助我吗?很抱歉出现任何错误或混淆,但现在是凌晨4点:)

这听起来很明显,但请尝试“printf”来验证文件名和路径。可能是空格有问题。顺便说一句,您可以使用脚本来计算文件的大小(如果您在linux中,您有很多命令来执行),并将值作为参数传递给程序。

请参阅malloc()。它只为
文件路径
分配
sizeof(command)-command\u SIZE
。但它需要存储
strlen(目录)+sizeof(命令)-command\u SIZE
strncat()
printf()
不检查数组是否会越界,以便获得正确的
文件路径输出


您可以在
get\u file\u size()
中用
/files/text.txt
替换
file\u name
来检查它。

请举一个其他人可以测试的例子,也请参见此处的说明。胡乱猜测,因为您使用的是相对路径:服务器进程的工作目录可能不是您所认为的。使用
getcwd
获取并打印当前工作目录;“<代码> ./file /Test.txt ”是否存在于该目录中?在计算文件大小时,请考虑函数<代码> fStasePosie()/<代码>和<代码> fGePosith](< /代码>)。其中使用的整数是操作系统的正确大小
long
,如
fseek()
ftell()
所用,可能不够。@Wintermute证明你是对的,我检查了工作目录,发现我把files目录放在了它的一个子目录(\Release)中,我认为这是正确的。Qmick Zh,您所说的有道理,但它不需要您所建议的修改,只需将文件移动到正确的工作目录中(并打印正确的文件维度…如何?)
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;
}