2017-05-03 1 views
2

strtok를 strcpy를 통해이 포럼의 다른 답변에서 제안한대로 복사하려고 할 때. 나는 각각의 번호를 얻지 못한다. 파일 형식은 각 줄마다 43,789,127.0.0.1과 같습니다. 그러나 127.0.0.1이어야하는 임시 직원 [2] 위치에서 127이됩니다. 내가 여기서 무엇을 놓치고 있니? const char s[1] = ","; 널 종결하지 않고, (1)의 크기를 가지고 그것을 정의strtok에 의해 반환 된 토큰을 복사하는 방법

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

'CONST 문자 S [1] = ""; '->'CONST 문자 S [2] = "" ; 또는'const char s [] = ","; ' – BLUEPIXY

+2

파일의 마지막 줄부터 결과를 얻을 수 있습니다. 이전 행 데이터를 덮어 씁니다. –

+0

나는 이미 그 것을 인정합니다. –

답변

6

s 적당한 C 문자열 아니다.

사용이 대신 : 미만 2 개 쉼표로 라인이 당신이 strtok()이 아닌 NULL 포인터를 반환 확인하지 않는 프로그램이 정의되지 않은 동작이 발생할 것

const char *s = ","; 

참고. 여기 sscanf()를 사용하여 대안은 다음과 같습니다 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; 
} 

참고 그러나 것이다.

strtok()도 분리 기호 시퀀스를 단일 분리 기호로 처리하므로 공백에 대해서는 괜찮지 만 ,에 대해서는 올바르지 않을 수 있습니다.

1

다음과 같은 제안 코드 :

  1. 깔끔하게
  2. 가 지속적으로
  3. 적절 수평 및 수직
  4. 가 제대로을 검사 게시 된 코드에서 알려진 모든 문제를 해결 이격되어 들여 쓰기 컴파일 오류 처리
  5. 은 fil의 모든 줄에서 매개 변수를 올바르게 표시합니다. E
  6. 불필요한 변수

이제 코드를 제거

#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 
관련 문제