【问题标题】:calculating the file size from the file path in a string从字符串中的文件路径计算文件大小
【发布时间】: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()。其中使用的整数是操作系统的正确大小。 longfseek()ftell() 使用的可能不够用。
  • @Wintermute 原来你是对的,我检查了工作目录,发现我把文件目录放在它的子目录(\Release)中,这是可执行文件所在的位置,我想是正确的。

标签: c file network-programming


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    查看你的 malloc()。它只为file_path 分配sizeof(command)-COMMAND_SIZE。但它需要存储strlen(DIRECTORY) + sizeof(command)-COMMAND_SIZEstrncat()printf() 不检查数组是否超出范围,因此您会得到正确的输出 file_path

    您可以在get_file_size() 中将file_name 替换为./files/text.txt 进行检查。

    【讨论】:

    • Qmick Zh,你说的是有道理的,但它无需你建议的修改就可以工作,只需将文件移动到正确的工作目录中(并打印正确的文件尺寸......怎么样? )
    猜你喜欢
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多