stat() giving wrong directory size in c

后端 未结 3 762
庸人自扰
庸人自扰 2021-01-21 00:16

I need to find the size of a file or a directory whatever given in the commandline using stat(). It works fine for the files (both relative and absolute paths) but when I give a

3条回答
  •  -上瘾入骨i
    2021-01-21 00:56

    Yes. opendir() + loop on readdir()/stat() will give you the file/directory sizes which you can sum to get a total. If you have sub-directories you will also have to loop on those and the files within them.

    To use du you could use the system() function. This only returns a result code to the calling program so you could save the results to a file and then read the file. The code would be something like,

    system("du -sb dirname > du_res_file");
    

    Then you can read the file du_res_file (assuming it has been created successfully) to get your answer. This would give the size of the directory + sub-directories + files in one go.

提交回复
热议问题