我必须编写一个程序,wchich以二进制模式打开一个文件并计算它的大小。我只需要编写一个函数就可以做到这一点,它只需具有一个参数,即数据文件的名称。

我插入文件名,并不断收到错误消息,但我不知道为什么。

这是功能

long getFileSize (char * fileName) {

    long size_Of_File = 0;
    FILE *data_file;
    data_file = fopen(fileName, "rb");

    if (data_file == NULL) {
            printf("Error opening the file!\n");
            return -1;
    };

    fseek(data_file, 0, SEEK_END);
    size_Of_File = ftell(data_file);

    fclose(data_file);
    return size_Of_File;
}


和函数main()(如果需要):

int main () {
    char * fileName;
    fileName = (char *) malloc (50 * sizeof(char));  //maximum length of the filename is 50 symbols
    long file_size;


    if (fileName != NULL) {
        printf ("Please write the name of the data file (with \'.txt\' prefix): ");
        fgets(fileName, 50, stdin);
        file_size = getFileSize(fileName);
        printf ("The size of the file is %li bytes.\n", file_size);
    } else {
        printf ("Could not allocate memory!\n");
    };

   free(fileName);
   return 0;
}


我在这里先向您的帮助表示感谢。

最佳答案

正如Tom Karzes所提到的,您将需要从字符数组中删除换行符字节。

一种简单的方法是一次遍历一个字节的字符数组,检查当前字节是否为换行符,并将其替换为字符串终止符'\ 0'。

//...

fgets(fileName, 50, stdin);

//Replace the first occurrence of \n with \0 to end the string.
for ( int i=0; i<50; i++ ) {
  if ( fileName[i] == '\n' ) {
    fileName[i] = '\0';
    break;
  }
}

//...

关于c - 无法弄清楚为什么我在C中打开文件时总是出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46995924/

10-09 08:10
查看更多