2017-05-03 83 views
2

當我嘗試通過strcpy將strtok複製到本論壇中的其他答案時。我沒有得到相應的號碼。文件格式在每個特定的行上類似於這個439127.0.0.1。不過,我在temp [2]位置得到127,應該是127.0.0.1。我在這裏錯過了什麼?如何通過strtok在c中複製返回的令牌

FILE *f = fopen("somefile", "r"); 
char *temp[3]; 
temp[0] = malloc(20); 
temp[1] = malloc(20); 
temp[2] = malloc(20); 
const char s[1] = ","; 
char *pch; 
if(f != NULL) 
{ 
    char line[1024]; 
    while(fgets(line, sizeof line, f) != NULL) 
    { 
    pch = strtok(line, s); 
    for(int i = 0; i<3; i++) 
    { 
     strcpy(temp[i],pch); 
     pch = strtok (NULL, s); 
    } 
    } 
    fclose(f); 
} else 
{ 
    perror("somefile"); 
} 
for(int i = 0; i<3; i++) 
{ 
    printf ("%s\n",temp[i]); 
} 
+8

'常量字符S [1] = 「 」;' - >'常量字符S [2] =「,」 ;'或'const char s [] =「,」;' – BLUEPIXY

+2

您只會從文件的最後一行獲得結果。以前的行數據將被覆蓋。 –

+0

那麼我已經知道這件事了。 –

回答

6

s是不正確的C字符串:const char s[1] = ",";定義它爲具有尺寸爲1,如果沒有空終止。

使用這個代替:

const char *s = ","; 

注意,只有不到2個逗號線會導致程序有不確定的行爲,你不檢查strtok()返回一個非NULL指針。下面是使用sscanf()替代:

#include <stdio.h> 

int main(void) { 
    FILE *fp = fopen("somefile", "r"); 
    char temp[3][20]; 
    if (fp != NULL) { 
     char line[1024]; 
     while (fgets(line, sizeof line, fp) != NULL) { 
      if (sscanf(line, "%19[^,],%19[^,],%19[^\n]", temp[0], temp[1], temp[2]) == 3) { 
       printf("%s\n%s\n%s\n\n", temp[0], temp[1], temp[2]); 
      } 
     } 
     fclose(fp); 
    } 
    return 0; 
} 

注意然而,由於sscanf()需要用於%[^,]轉換說明一個非空字符串上面的代碼將無法解析用空字段如,,線。

還要注意strtok()也不適合這樣的解析,因爲它將分隔符的序列看作是一個單獨的分隔符,這對於空白空間是可以的,但對於,可能不正確。

1

下面提出的代碼:

  1. 完全編譯
  2. 一致地縮進
  3. 適當地橫向和縱向間隔開的
  4. 校正所有在張貼代碼
  5. 適當檢查的已知問題並處理錯誤
  6. 正確顯示來自fil中所有行的參數È
  7. 消除不需要的變量

和現在的代碼

#include <stdio.h> // fopen(), fclose(), fgets(), perror() 
#include <stdlib.h> // exit(), EXIT_FAILURE 
#include <string.h> // strtok(), strcpy() 

#define MAX_LENGTH  20 
#define MAX_PARAMETERS 3 

int main(void) 
{ 
    FILE *f = fopen("somefile", "r"); 
    if(!f) 
    { 
     perror("fopen to read somefile failed"); 
     exit(EXIT_FAILURE); 
    } 

    // implied else, fopen successful 

    char *temp[ MAX_PARAMETERS ]; 

    if(NULL == (temp[0] = malloc(MAX_LENGTH))) 
    { 
     perror("malloc failed"); 
     exit(EXIT_FAILURE); 
    } 

    if(NULL == (temp[1] = malloc(MAX_LENGTH))) 
    { 
     perror("malloc failed"); 
     exit(EXIT_FAILURE); 
    } 

    if(NULL == (temp[2] = malloc(MAX_LENGTH))) 
    { 
     perror("malloc failed"); 
     exit(EXIT_FAILURE); 
    } 

    char line[1024]; 
    while(fgets(line, sizeof line, f)) 
    { 
     int i; 
     char *pch = strtok(line, ","); 

     for(i = 0; i<3 && pch; i++) 
     { 
      strcpy(temp[i], pch); 
      pch = strtok (NULL, ","); 
     } 

     if(MAX_PARAMETERS != i) 
     { 
      printf("failed to extract all parameters from line: %s\n", line); 
     } 

     else 
     { 
      for(int j = 0; j<MAX_PARAMETERS; j++) 
      { 
       printf("%s\n", temp[j]); 
      } 
     } 
    } 

    fclose(f); 
} // end function: main