我正在使用c++对ftp服务器进行编程,我需要能够以以下形式获取有关文件的所有信息:

sent: drwxr-xr-x 1000 ubuntu ubuntu 4096 May 16 11:44 Package-Debug.bash

这样我就可以发送给客户我部分成功地做到了这一点,但遇到了一些问题。这是我的代码的一部分:
void Communication::LISTCommand() {
DIR *directory;
struct dirent *ent;
char path[100];
strcpy(path, this->path.c_str());  //this->path can be different from current working path

/*if (chdir(path) == -1) {
    perror("Error while changing the working directory ");
    close(clie_sock);
    exit(1);
}*/

directory = opendir(path);
struct tm* clock;
struct stat attrib;
struct passwd *pw;
struct group *gr;
string line;
char file_info[1000];

.....

while ((ent = readdir(directory)) != NULL) {
    line.clear();
    stat(ent->d_name, &attrib);

    clock = gmtime(&(attrib.st_mtime));
    pw = getpwuid(attrib.st_uid);
    gr = getgrgid(attrib.st_gid);
    if (S_ISDIR(attrib.st_mode))
        line.append(1, 'd');
    else line.append(1, '-');
    if (attrib.st_mode & S_IRUSR)
        line.append(1, 'r');
    else line.append(1, '-');
    if (attrib.st_mode & S_IWUSR)
        line.append(1, 'w');
    else line.append(1, '-');
    if (attrib.st_mode & S_IXUSR)
        line.append(1, 'x');
    else line.append(1, '-');
    if (attrib.st_mode & S_IRGRP)
        line.append(1, 'r');
    else line.append(1, '-');
    if (attrib.st_mode & S_IWGRP)
        line.append(1, 'w');
    else line.append(1, '-');
    if (attrib.st_mode & S_IXGRP)
        line.append(1, 'x');
    else line.append(1, '-');
    if (attrib.st_mode & S_IROTH)
        line.append(1, 'r');
    else line.append(1, '-');
    if (attrib.st_mode & S_IWOTH)
        line.append(1, 'w');
    else line.append(1, '-');
    if (attrib.st_mode & S_IXOTH)
        line.append("x ");
    else line.append("- ");

    sprintf(file_info, "%s%d %s %s %d %s %d %02d:%02d %s\r\n", line.c_str(), pw->pw_uid,
            pw->pw_name, gr->gr_name, (int) attrib.st_size, getMonth(clock->tm_mon).c_str(),
            clock->tm_mday, clock->tm_hour, clock->tm_min, ent->d_name);

    if (send(c_data_sock, file_info, strlen(file_info), 0) == -1) {
        perror("Error while writing ");
        close(clie_sock);
        exit(1);
    }

    cout << "sent: " << file_info << endl;
}

.....

}

当path变量与当前工作路径不同时,此代码将不起作用。 Valgrind说,有许多跳转取决于未归一化的值等,并且文件列表包含错误的值-仅文件名和大小正确。当我将当前工作目录更改为path变量的内容时,它不会报告任何错误,但是文件列表仍然包含错误的信息。我真的不知道我的代码有什么问题,所以非常感谢任何帮助。

最佳答案

当你做

stat(ent->d_name, &attrib);

您应该记住ent->d_name仅包含文件名,而不包含完整路径。因此,如果要列出与程序当前目录不同的目录中的文件,则需要构造一个完整的路径以供使用。

最简单的解决方案可能是做类似的事情
std::string full_path = path;
full_path += '/';
full_path += ent->d_name;

if (stat(full_path.c_str(), &attrib) != -1)
{
    // Do your stuff here
}

10-07 19:25
查看更多