给定一个文本文件,找到其大小(以字节为单位)。
例子:
Input : file_name = "a.txt"
Let "a.txt" contains "geeks"
Output : 6 Bytes
There are 5 bytes for 5 characters then an extra
byte for end of file.
Input : file_name = "a.txt"
Let "a.txt" contains "geeks for geeks"
Output : 16 Bytes
这个想法是在C语言中使用fseek()在C语言中使用ftell。使用fseek()将文件指针移动到末尾,然后使用ftell()找到其位置,该位置实际上是字节大小。
// C program to find the size of file
#include
long int findSize(char file_name[])
{
// opening the file in read mode
FILE* fp = fopen(file_name, "r");
// checking if the file exist or not
if (fp == NULL) {
printf("File Not Found!\n");
return -1;
}
fseek(fp, 0L, SEEK_END);
// calculating the size of the file
long int res = ftell(fp);
// closing the file
fclose(fp);
return res;
}
// Driver code
int main()
{
char file_name[] = { "a.txt" };
long int res = findSize(file_name);
if (res != -1)
printf("Size of the file is %ld bytes \n", res);
return 0;
}
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。