2013-08-22 2 views
-1

내가 전에 비슷한 질문을했는데, 링크는 여기에있다. C-Read txt into txt fileC - 읽기 txt 및 배열에 쓰기

배열의 첫 번째 열에 "크기"값이 부여 된 코드에 약간의 문제가 있음을 확인했습니다.

나는 누군가를 도울 수 있기를 바랍니다. 여기에 새로운 것을 게시하고 싶습니다.


저는 /user/test/key.txt 디렉토리에 txt 문서가 있습니다. txt의 내용은 다음과 같습니다.

10 21 34 45 29 38 28 
(blank line) 
29 47 28 32 31 29 20 12 24 
(blank line) 

이 숫자를 txt에서 읽고 두 줄짜리 배열로 쓰고 싶습니다. 배열의 길이는 txt의 긴 행에 따라 다를 수 있습니다. 그리고 그것은 배열에 다음과 같이 될 수 있습니다

10 21 34 45 29 38 28 0 0 
29 47 28 32 31 29 20 12 24 

감사합니다!

+0

그래서 숫자 라인이 가장 긴 라인과 같은 수의 엔트리를 가지기를 원한다면, 필요하다면 끝에 0 개의 엔트리가 채워지겠습니까? – Jiminion

+0

먼저 뭔가를 쓰고 작동하도록 최선을 다해야합니다. – dasblinkenlight

+0

@ 짐 예. 감사합니다. –

답변

1

당신이 명시 적으로 받아 들인 답은 무엇을 의미하며 어떻게 든 특정 행에 포함 된 열의 수를 결정해야하기 때문에 좋은 생각입니다. 또 다른 단점은 모든 행의 특수 값이 끝을 결정하도록하는 것입니다 (문자열의 '\0'처럼). 코드를 다음과 같이 바꿀 수 있습니다 :

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int getColCount(FILE *fin){ 
    long fpos = ftell(fin); 
    int count = 0; 
    char buff[BUFSIZ]; 
    while(fgets(buff, sizeof(buff), fin)){ 
     char *p; 
     for(p=strtok(buff, " \t\n");p;p=strtok(NULL, " \t\n")) 
      ++count; 
     if(count)break; 
    } 
    fseek(fin, fpos, SEEK_SET); 
    return count; 
} 

int main(void){ 
    FILE *fp; 
    int *key1[2]; 

    if((fp = fopen("/Users/doc/test.txt", "rt")) == NULL){ 
     printf("\nCannot open file"); 
     exit(1); 
    } 

    for(int i = 0; i < 2; ++i){ 
     int size = getColCount(fp); 
     // size+1 is still necessary, the additional element is now needed for the delimiting value instead of the number of elements 
     key1[i] = malloc((size+1)*sizeof(int)); 
     /* CHANGE: don't store size in col 0 
     if(key1[i]){ 
      key1[i][0] = size;//length store top of row 
     } else { 
      fprintf(stderr, "It was not possible to secure the memory.\n"); 
      exit(2); 
     } 
     now we just do: */ 
     if(!key1[i]){ 
      fprintf(stderr, "It was not possible to secure the memory.\n"); 
      exit(2); 
     } 
     /* CHANGE: we start with index 0 */ 
     //for(int j = 1; j <= size ;++j){ 
     for(int j = 0; j < size ;++j){ 
      fscanf(fp, "%d", &key1[i][j]); 
     } 
     /* CHANGE: we add a final value to determine the end of the row */ 
     key[i][size] = -1; // choose a value that cannot occur in your data 
    } 
    fclose(fp); 
    {//check print and dealocate 
     for(int i = 0; i < 2 ; ++i){ 
      for(int j = 1; j <= key1[i][0]; ++j) 
       printf("%d ", key1[i][j]); 
      printf("\n"); 
      free(key1[i]); 
     } 
    } 
    return 0; 
} 
+0

@Ingo Leonhardt. 나는 아주 약간의 변화를 만들었고 효과가 있었다. –

+0

나에게 말해줘. 다음번에 그것을 읽을 다음 사람을 위해 포스트를 정정하게되어 기쁘다 –

+0

@ Jiayi Guo'malloc (size + 1 * sizeof (int))'는 여전히 필연적이다. 이유를 설명하기 위해 코드에 주석을 추가했습니다 –