我正在写一个简单的程序,用于构建当前目录的目录索引。如何把不同的C字符串放在一个漂亮的格式?
每个文件都有两个用于文件名和最后修改时间的char *对象,以及一个用于文件大小的整数。
我想把所有这些放在一个大的string
或char*
。
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
using namespace std;
char* file_info(char*);
int main(void)
{
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
file_info(dir->d_name);
}
closedir(d);
}
return(0);
}
char* file_info(char* file) {
if(file[0] != '.') {
struct stat sb;
if (stat(file, &sb) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
char* lm = ctime(&sb.st_mtime);
*lm = '\0';
stringstream ss;
ss << file << " " << lm << " " << sb.st_size;
cout << ss.str() << endl;
}
return lm;
}
我想返回char*
是,在这种格式具有内容的对象:
homework-1.pdf 12-Sep-2013 10:57 123K
homework-2.pdf 03-Oct-2013 13:58 189K
hw1_soln.pdf 24-Sep-2013 10:36 178K
hw2_soln.pdf 14-Oct-2013 09:37 655K
的间距是这里的主要问题。 我怎样才能轻松修正它? 我尝试到目前为止是
const char* file_info(char* file) {
if(file[0] != '.') {
struct stat sb;
if (stat(file, &sb) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
char* lm = ctime(&sb.st_mtime);
string lastmod(lm);
lastmod.at(lastmod.size()-1) = '\0';
stringstream ss;
string spacing = " ";
ss << file << spacing.substr(0, spacing.size() - sizeof(file)) << lastmod << spacing.substr(0, spacing.size() - lastmod.size()) << sb.st_size;
cout << ss.str() << endl;
return ss.str().c_str();
}
else {
return NULL;
}
}
,但它没有工作,我用绳子工作如此糟糕。
不要返回'char const *'为了爱的右边缘。返回'std :: string'。 – rightfold
这是C++,而不是C.你应该改变标题来反映这一点。 –
而不是尝试和每个迭代组成一个完整的字符串,与每个字段(名称,日期/时间,大小)填充结构并将它们放入一个向量。然后迭代保存每个字段的最大尺寸的向量。然后你知道每个字段的最大尺寸,并且你可以格式化这些线条,使它们在第二遍中对齐并正确分隔。 – Duck