如何将文件目录和文件大小输出到txt文件。 [英] How do I output file directory and file size to a txt file.
本文介绍了如何将文件目录和文件大小输出到txt文件。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以输出文件目录。我想广告文件大小也是输出。
我尝试过:
I am able to output file directory. I would like to ad file size to the output as well.
What I have tried:
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
/*function... might want it in some class?*/
int getdir (string dir, vector<string> &files)
{
DIR *dp;
struct dirent *dirp;
if((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
while ((dirp = readdir(dp)) != NULL) {
files.push_back(string(dirp->d_name));
}
closedir(dp);
return 0;
}
int main()
{std::ofstream outputFile;
outputFile.open("Files.txt");
string dir = string(".");
vector<string> files = vector<string>();
getdir(dir,files);
for (unsigned int i = 0;i < files.size();i++) {
outputFile << files[i] << endl;
}
return 0;
}
推荐答案
创建一个FileItem
类,其中包含名称和大小(以字节为单位)。在阅读每个目录条目时,您需要创建一个新的FileItem
对象。添加名称,然后测试它是文件还是目录。如果是文件,则获取其大小并将其添加到对象。然后,您可以构建对象的向量(或指向它们的指针),主方法可以使用这些向量写入输出文件,或在屏幕上显示。
Create aFileItem
class that will contain the name and the size in bytes. As you read each directory entry you need to create a newFileItem
object. Add in the name and then test if it is a file or a directory. If it is a file then get its size and add that to the object. You can then build a vector of your objects (or pointers to them) which your main method can use to write to the output file, or display on screen.
这篇关于如何将文件目录和文件大小输出到txt文件。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文