2013-05-16 1 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는 불필요한 값에 의존하는 점프가 많으며 파일 목록에 잘못된 값이 들어있어 파일 이름과 크기 만 맞다고 말합니다. 현재 작업 디렉토리를 path 변수의 내용으로 변경하면 오류를보고하지 않지만 파일 목록에는 여전히 잘못된 정보가 포함됩니다. 나는 정말로 어떤 코드가 잘못 되었는가에 대한 단서가 없기 때문에 어떤 도움을 많이 주신다.

답변

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

관련 문제