2013-06-22 130 views
-1

當我運行這個程序。文件描述符返回值爲-1,因此程序終止。我不知道爲什麼會發生這種情況。由於pid值正是我想要打開的文件的名稱。無法打開文件,文件描述符返回-1值

const char *psyn = "product/productId:"; 
char line[100]; 
pFile = fopen ("pids.txt" , "r"); 
if (pFile == NULL) perror ("Error opening file"); 
else { 
    while(fgets (line , sizeof(line) , pFile)) 
     { 
     if (strstr(line, psyn) == line) 
      { 
      leng = strlen(line); 
        if(line[leng-1] == '\n') 
         line[leng-1] = 0; 
        if(line[0] == '\n') 
         line[0] = 0; 
      pid = line+strlen(psyn)+1; 
          strcat(pid,t); 

      leng = strlen(pid); 
        if(pid[leng-1] == '\n') 
         pid[leng-1] = 0; 

      fd = open(pid, O_RDWR, 0644); 
       if (fd == -1) 
           cout<<"eror in file \n"; 
       else { //.. rest of the program} 
+0

同我做到了打印錯誤(如果FD == - 1)... 「在文件eror」 – amian

+0

什麼errno'的'fopen'後'值 – DevZer0

+0

的fopen工作完全失敗..這是產生錯誤的代碼fd = open(pid,O_RDWR,0644); if(fd == -1) cout <<「檔案中的錯誤\ n」; – amian

回答

0

pid = line+strlen(psyn)+1;
引起了我的懷疑。首先strlen()在這裏效率不高。其次,+1比字符串長。

 
int opt_verbose; // from -v option 

    char psyn[] = "product/productId:"; // array, not pointer 
    char line[100]; 
    FILE *pFile = fopen ("pids.txt" , "r"); 
    if (pFile == NULL) perror ("Error opening file"); 
    else { 
     while(fgets (line , sizeof(line) , pFile)) 
     { 
      char *s = strstr(line, psyn); 
      if (s == line) 
      { 
       int leng; 
       for (leng = strlen(line); 
         leng > 0 && isspace(line[leng-1]); 
         leng--) 
        line[leng-1] = '\0'; 

       char *pid = line + sizeof(psyn) - 1; // sizeof without \0 
       strcat(pid,t); 
       leng = strlen(pid); 
       if(pid[leng-1] == '\n') 
        pid[leng-1] = 0; 

       if (opt_verbose) 
        printf("VERBOSE: opening %s\n", pid); 
       int fd = open(pid, O_RDWR, 0644); 
       if (fd == -1) 
       {  // perror is usually not sufficiently detailed 
        printf("ERROR: open \"%s\" failed: (%d) %s\n", 
             pid, errno, strerror(errno)); 
          // \"%s\" nicely shows unexpected spaces in paths. 
        continue; 
       }