[英]Can't figure out why do I keep getting an error opening a file in C
I have to write a program, wchich opens a file in binary mode and calculates the size of it. 我必须编写一个程序,wchich以二进制模式打开一个文件并计算它的大小。 I have to write only one function to do that and it only has to have one parameter, which is the name of the data file.
我只需要编写一个函数就能做到这一点,它只需具有一个参数,即数据文件的名称。
I insert the name of the file and keep getting the error message and I can't figure out why. 我插入文件名并不断收到错误消息,但我不知道为什么。
Here's the function 这是功能
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;
}
and the function main() if you need it: 和函数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;
}
Thanks for the help in advance. 我在这里先向您的帮助表示感谢。
As Tom Karzes mentioned, you will need to remove the newline byte from the array of characters. 正如Tom Karzes所提到的,您将需要从字符数组中删除换行符字节。
A simple way you could do this is to step through the array of characters one byte at a time, checking to see if the current byte is the newline character and replacing it with the string terminator byte '\\0'. 一种简单的方法是一次遍历一个字节的字符数组,检查当前字节是否为换行符,并将其替换为字符串终止符'\\ 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;
}
}
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.