显示文件大小 [C]

Displaying size of a file [C]

我正在制作一个简单的套接字程序,用于将文本文件或图片文件发送到连接到端口的另一个套接字。但是,我还想将文件的大小发送到客户端套接字,以便它知道要接收多少字节。

我还想实现一些可以发送一定数量的字节而不是文件本身的东西。例如,如果我要发送的文件是 14,003 字节,而我想发送 400 字节,那么只会发送 400 字节。

我正在实施这样的事情:

 #include <stdio.h>

 int main(int argc, char* argv[]) {
     FILE *fp;
     char* file = "text.txt";
     int offset = 40;
     int sendSize = 5;
     int fileSize = 0;

     if ((fp = fopen(file, "r")) == NULL) {
         printf("Error: Cannot open the file!\n");
         return 1;
     } else {
         /* Seek from offset into the file */
         //fseek(fp, 0L, SEEK_END);
         fseek(fp, offset, sendSize + offset); // seek to sendSize
         fileSize = ftell(fp); // get current file pointer
         //fseek(fp, 0, SEEK_SET); // seek back to beginning of file
     }

     printf("The size is: %d", fileSize);
 }

offset 几乎要将 40 个字节放入文件,然后将任何 sendSize 字节发送到另一个程序。

我一直得到 0 而不是 5 的输出。这背后有什么原因吗?

你可以试试这个。

#include <stdio.h>

int main(int argc, char* argv[]) {
    FILE *fp;
    char* file = "text.txt";
    int offset = 40;
    int sendSize = 5;
    int fileSize = 0;

    if ((fp = fopen(file, "r")) == NULL) {
        printf("Error: Cannot open the file!\n");
        return 1;
    } else {
        fseek(fp, 0L, SEEK_END);
        fileSize = ftell(fp);
    }

    printf("The size is: %d", fileSize);
}

我认为您的 Seek 由于第三个参数而无法工作: 尝试用
寻找 (fp, offset, SEEK_SET);

因为他将尝试使用数字 sendSize+Offset 作为 "origin" 常量,它将与下面的 3 个常量值(它是 0、1 或 2)进行比较,因为没有什么比得上它似乎一直 return 0。

http://www.cplusplus.com/reference/cstdio/fseek/

参数

流、偏移、原点

用作偏移参考的位置。它由专门定义的下列常量之一指定用作此函数的参数:

常量参考位置
SEEK_SET 文件开头
SEEK_CUR 文件指针的当前位置
SEEK_END文件结束

fseek() 到最后,然后是 ftell() 方法是一种获取文件大小的合理可移植方法,但不能保证正确。它不会透明地处理换行符/回车符 return 转换,因此,该标准实际上并不保证 ftell() 中的 return 除了寻求相同的目的之外的任何目的都是有用的位置。

唯一可移植的方法是读取文件直到数据用完并记录字节数。或者 stat() 使用(非 ANSI)Unix 标准函数的文件。

您可能以文本模式打开文件 Windows can open a file in text mode even without the "t" option

并且您不能使用 ftell() 获取以文本模式打开的文件的大小。根据 7.21.9.4 C 标准的 ftell 函数

For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

即使它 return 文件的 "size",翻译成 "text" 也可能改变读取的实际字节数。

使用 fseek() 查找二进制文件的末尾也不便携或不符合标准。根据 7.21.9.2 fseek 函数:

A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.