【发布时间】:2013-01-28 18:58:46
【问题描述】:
我不确定 C 是否可以做到这一点,但我希望我可以制作一个程序来查看目录,并打印出目录的所有内容以及每个文件的文件大小.因为我希望它看起来像这样(可能):
文件名.txt -- 300 字节
filename2.txt -- 400 字节
filename3.txt -- 500 字节
等等。
到目前为止,我创建了一个可以打开文件的程序,它会打印字节,但它不会读取整个目录,我必须具体说明我要读取的文件..(即不是我想要的)。
这是我目前所拥有的:
#include <stdio.h>
int main(){
FILE *fp; // file pointer
long fileSize;
int size;
// opens specified file and reads
fp = fopen( "importantcommands.txt", "rw" );
if( fp == NULL ){
printf( "Opening file error\n" );
return 0;
}
// uses fileLength function and prints here
size = fileLength(fp);
printf( "\n Size of file: %d bytes", size );
fclose(fp);
return 0;
}
int fileLength( FILE *f ){
int pos;
int end;
// seeks the beginning of the file to the end and counts
// it and returns into variable end
pos = ftell(f);
fseek (f, 0, SEEK_END);
end = ftell(f);
fseek (f, pos, SEEK_SET);
return end;
}
请帮忙。
【问题讨论】:
-
刚刚编辑显示平台。 :) Windows 7!
-
有用的错误信息很重要:
fp = fopen( name, mode ); if( fp == NULL ) { perror( name ); }
标签: c file printing size names