2013-05-16 109 views
1

我使用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; 
} 

..... 

} 

當路徑變量是從當前工作路徑不同,此代碼不能正常工作。 Valgrind說有很多跳轉取決於未初始化的值等,並且文件列表包含錯誤值 - 只有文件名和大小是正確的。當我將當前工作目錄更改爲路徑變量的內容時,它不會報告任何錯誤,但文件列表仍包含錯誤信息。我真的不知道我的代碼有什麼問題,所以任何幫助都非常感謝。

回答

1

當你

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 
} 
+0

非常感謝實際上是有我的代碼中多了一個錯誤的地方,但現在所有的作品。 – user2274361