2012-04-22 6 views
0

폴더의 일부 파일 수정 날짜를 알아야합니다. 작동하지만 모든 유형의 파일에서는 작동하지 않습니다. 예를 들어 .c, .txt와 작동하지만 .mp4, .jpg 및 .mp3과 같은 다른 유형에서는 작동하지 않습니다 (작성중인 응용 프로그램은 일반적으로 멀티미디어 파일과 함께 작동해야합니다). "시간을 표시 할 수 없습니다."라는 내용이 출력되므로 stat()에 문제가 있다고 가정합니다. 감사.stat()에서 오류가 발생했습니다

#include <stdio.h> 
#include <stdlib.h> 
#include <dirent.h> 
#include <string.h> 
#include <time.h> 
#include <sys/types.h> 
#include <sys/stat.h> 

char parola[12]="", hash[32]="", esadecimale[1000]="", system3[100]="./md5 "; 
int i, len, len2; 
int bytes; 
char cwd[1024]; 

int main(void) 
{ 
char t[100] = ""; 
struct stat b; 
DIR *dp; 
char destinationFolder[100] = "/Users/mattiazeni/Desktop/Prova/"; //Me la passa da sopra 
struct dirent *dir_p; 
dp = opendir(destinationFolder); 
if (dp == NULL) exit(1); 

len = strlen(destinationFolder); 

for (i=0;i<len;i++) { 
    system3[i+6]=destinationFolder[i]; 
} 

while((dir_p = readdir(dp)) != NULL) { 
    if (dir_p -> d_name[0] != '.') { 
     //printf("%s\n", dir_p -> d_name); 
     len2 = strlen(dir_p -> d_name); 
     for (i=0;i<len2;i++) { 
      if (dir_p -> d_name[i] == ' '){ //Mi serve per correggere i nomi dei file con spazi 
       system3[i+len+6]='\\'; 
      } 
      else system3[i+len+6]=dir_p -> d_name[i]; 
     } 
     system(system3); //Passa il valore a md5 che calcola l'hash e lo stampa nel file che ci serve insieme al persorso/nome del file 

     FILE *fp; 
     if((fp=fopen("userDatabase.txt", "ab"))==NULL) { 
      printf("Error while opening the file..\n"); 
      fclose (fp); 
     } 
     else { 
      if (!stat(dir_p -> d_name, &b)) { 
      strftime(t, 100, "%d/%m/%Y %H:%M:%S", localtime(&b.st_mtime));   //C'è ancora qualche errore!! 
      fprintf(fp, "%s", t);   
      } 
      else { 
       perror(0); 
       fprintf(fp, "error"); 
      } 
      fprintf(fp, " initialized"); 
      fprintf(fp, "\n"); 
     } 
     fclose (fp); 
     for (i=len+6;i<len+6+len2;i++) { 
      system3[i]=' '; 
     } 
    } 
} 
closedir(dp); 
return 0; 
} 
+3

어떤 오류가 발생했는지 알기 위해 "시간을 표시 할 수 없습니다"printf 대신'perror'를 사용하십시오. – Mat

답변

3

사용 perror() :

는 코드입니다. 또한 st_mtime을 사용하지 않아야합니까? dir_p -> d_name 차례로 아마 때문에 현지화 문제로, 이는 존재하지 않기 때문에

stat: 
     On success, zero is returned. 
     On error, -1 is returned, and errno is set appropriately.

99 % 확신이있다.

당신은 같은 것을 할 수있는 : 또한

fprintf(stderr, 
     "Unable to stat %s\n", 
     dir_p->d_name); 
perror(0); 

을; 파일 상태를 확인하는 경우 ->f_name이 아니고 ->d_name이 아니어야합니까? - (. 당신은 파일 이름 오프 물론에 대한 d_name을 사용하지 않으면 는)

그리고 당신의 fclose(fp) 당신의 fp == NULL 검사를 벗어납니다. 돌아 오지 않거나 달리 흐름을 중단하지 않으면 fopen이 실패하면 SIGSEGV가 발생할 위험이 있습니다.


편집 : 다음과 같이하면 어떻게됩니까?

#include <unistd.h> 

char cwd[1024]; 

... 


} else { 
    fprintf(stderr, 
      "Unable to stat '%s'\n", 
      dir_p->d_name); 
    perror(0); 

    if (getcwd(cwd, sizeof(cwd)) == NULL) { 
     perror("getcwd() error"); 
    } else { 
     fprintf(stderr, 
       "in directory '%s'\n", 
       cwd); 
    } 
} 

Edit2가 :

첫째; 나는 getcwd() != NULL==이어야한다고 말했습니다. 변경. (나에 의해 나쁜.)

코드의 문제. (몇 가지 더 있습니다)하지만 통계에 관한 - readdir에서 d_name을 사용합니다. 이것은 파일 이름입니다. dir + filename이 아닙니다. 그러므로; 당신은 예를 얻을 : 즉이되는

stat(dir_p->d_name, ...) 

:

stat("file.mp4", ...) 

가장 쉬운 빠른 수정 (더러운 THO) 다음과 같습니다

/* you need to terminate the system string after your for loop */ 
system3[i + len + 6] = '\0'; 

system(system3); 

if (!stat(system3 + 6, &b)) { 
+0

답장을 보내 주셔서 감사합니다. dir_p -> d_name은 어떤 파일이 들어 있는지 알기 위해 디렉토리를 스캔 한 다음 각 파일에 대해 수정 날짜를 알고 싶기 때문에 사용합니다. perror로 "No such file or directory"가 표시됩니다. 하지만 왜 파일이 ​​거기에 있는지 이해할 수 없습니다. 또한 md5 해시를 계산하는 파일 때문에 걱정하지 않아도됩니다. 문제는 날짜 만입니다. – phcaze

+0

@phcaze :'dir_p-> d_name'은 무엇으로 인쇄됩니까? 또한; 당신은 그 일을 약간 변경하면 현재 작업 디렉토리를 확인할 수 있습니다. 위의 새 코드와 같은 것을 사용하십시오. 무엇이 인쇄됩니까? – Morpfh

+0

dir_p-> d_name은 /Users/user/Desktop/file.mp4라는 파일 이름으로 경로를 인쇄합니다. 코드를 사용하면 "/Users/user/Desktop/file.mp4 getcwd() 오류 : 정의되지 않은 오류 : 0"이라는 화면에 인쇄됩니다. – phcaze

0

당신은) (STAT에 대한 완전한 경로 이름을 사용해야합니다 . . 합계는

... 
char bigbuff[PATH_MAX]; 

sprintf(bigbuff, "%s/%s", destinationFolder, dir_p->d_name); 

rc = stat (bigbuff, &b); 
... 
+0

예, 그게 문제였습니다! :) 감사. 하지만 왜 일부 파일에서만 오류가 발생합니까? – phcaze

0

이 파일에 대한 디렉토리를 검색하기 위해 최종 작업 코드에 관심이있는 디렉토리를 알고, 수정 날짜와 TXT 출력 파일을 인쇄하지 않습니다

#include <stdio.h> 
#include <stdlib.h> 
#include <dirent.h> 
#include <string.h> 
#include <time.h> 
#include <sys/types.h> 
#include <sys/stat.h> 

char system3[6]="./md5 "; 

int main(void) 
{ 
char t[100] = ""; 
char bigbuff[200]; 
struct stat b; 
char destinationFolder[100] = "/Users/mattiazeni/Desktop/Prova"; //Me la passa da sopra 
DIR *dp; 
struct dirent *dir_p; 
dp = opendir(destinationFolder); 
if (dp == NULL) exit(1); 
while((dir_p = readdir(dp)) != NULL) { 
    if (dir_p -> d_name[0] != '.') { 
     sprintf(bigbuff, "%s%s/%s",system3, destinationFolder, dir_p->d_name); 
     system(bigbuff); 

     FILE *fp; 
     if((fp=fopen("userDatabase.txt", "ab"))==NULL) { 
      printf("Error while opening the file..\n"); 
      fclose (fp); 
     } 
     else { 
      sprintf(bigbuff, "%s/%s", destinationFolder, dir_p->d_name); 
      if (!stat(bigbuff, &b)) { 
      strftime(t, 100, "%d/%m/%Y %H:%M:%S", localtime(&b.st_mtime));   //C'è ancora qualche errore!! 
      fprintf(fp, "%s", t);   
      } 
      else { 
       perror(0); 
       fprintf(fp, "error"); 
      } 
      fprintf(fp, "\n"); 
     } 
     fclose (fp); 
    } 
} 
closedir(dp); 
return 0; 
} 

도움 주셔서 감사합니다.