用C打印文件名及其'大小

cha*_*ilk 2 c printing size file names

我不确定C是否可以这样做,但我希望我可以创建一个程序来查看目录,并打印出目录的所有内容以及每个文件的文件大小.就像在我希望它看起来像这样(可能):

filename.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;
}
Run Code Online (Sandbox Code Playgroud)

请帮忙.

Car*_*rum 5

C当然可以做到 - ls(1)例如,命令可以用C语言编写.

要遍历目录,可以使用opendir(3)readdir(3)函数.不过,让shell为你做这件事可能更容易.

获取文件名,您可以通过将main定义为:将其作为命令行参数:

int main(int argc, char **argv)
Run Code Online (Sandbox Code Playgroud)

命令行参数将从argv[1].