2013-07-02 5 views
3

내 질문은 : 어떻게 내가 C에서 파일에서 한 줄의 문자열로 여러 줄에있는 문자열을 읽을 수 있습니까? 바이너리 맵을 만들려고하는데 제 1d 배열은 2 차원 배열로 표현됩니다. 그래서 내 "level_1.txt"에 있습니다파일에서 문자열을 읽고 그것을 배열로 어떻게 tokenize합니까?

//start of file 
WIDTH: 4 
HEIGHT: 5 

11,12,13,14, 
21,22,23,24, 
31,32,33,34, 
41,42,43,44, 
51,52,53,54, 
// eof 

와 나는 문자열 "11,12,13,14,21,22 ..."

을 좀하고 싶습니다 그리고 이것은이다 내 코드 :

int ImportMapDataFromFile(char *fileName, Map *self) 
{ 
    FILE *pFile; 
    char* myStr; 

    pFile = fopen(fileName, "r"); 

    // Check if the file exists: 
    if(pFile) 
    { 
     // scanf width and height 
     //fscanf(pFile, "%*s %i %*s %i", &self->width, &self->height); 
     /* 
     // this doesnt work 
     fscanf(pFile, "%*s %i %*s %i %s", &self->width, &self->height, &myStr); 
     */ 
     //printf("%i %i", self->width, self->height); 

     // initialise the array 
     (self->theScreenMap) = (Grid*)malloc(sizeof(Grid) * self->width * self->height); 

     // scan the whole remaining file 
     /* 
      I dont know how to do this. I tried using fscanf and had a look at fgets 
      but i cant seem to make it work sorry. 
     */ 


     // tokenise it 
     /* 
      Pretty sure i have to use strtok right? 
      http://www.cplusplus.com/reference/cstring/strtok/ 
     */ 

     // close it 
     fclose(pFile); 
     printf("%s \n", &myStr); 

     return TRUE; 
    } 
    else 
    { 
     fclose(pFile); 
     return FALSE; 
    } 
} 

내가 뭘 파일을 읽어 수행 1 2 개 라인에서 크기를 얻고 1D 배열을 생성하기 위해이 값을 사용하고 싶습니다. 그런 다음 한 번 완료되면 나머지 문자열을 읽고 배열에 할당하려고합니다. 예 :

theScreenMap[0] = 11; // first element has 1st token 
theScreenMap[1] = 12; 
theScreenMap[size - 1] = 54; // last element has last token 

나를 도와 주신 분들께 감사드립니다. 하지만 누구나 파일을 읽고 (바이너리 맵을 만들기 위해 어레이를 초기화하는) 더 나은 방법이 있다면, 그렇게 말해줘. 감사! :)

답변

4

이것은 원하는 것을 기본 구현 한 것입니다. 최종 결과는 '높이'만큼의 행을 읽고이를 연결합니다. 샘플에 대한

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define MAXSIZE 1024 
#define MAXLINE 256 

char mainArray[MAXSIZE]; 
char line[MAXLINE]; 

char *strdup(const char *s) { 
    char *str = malloc(strlen(s) + 1); 
    if(str) { strcpy(str, s); } 
    return str; 
} 

int main(int argc,char* argv[]) 
{ 
    int width,height; 
    unsigned int i=0; 
    unsigned int count=0; 
    char **grid; 
    FILE *fp = fopen("multiline.txt","r"); 
    if(!fp) {perror("multiline.txt");return -1;} 
    /* Read the width and height */ 
    fscanf(fp,"WIDTH: %d\n",&width); 
    fscanf(fp,"HEIGHT: %d\n",&height); 
    printf("Width: %d,\tHeight: %d\n\n",width,height); 
    while(!feof(fp)) 
    { 
     fgets(line,MAXLINE,fp); 
     strncat(mainArray,line,strlen(line)-1); /* get rid of newline */ 
     printf("Line:: %s",line); 
     printf("MainArray:: %s\n\n",mainArray); 
    } 
    /* Get the number of elements */ 
    for(i=0;i<strlen(mainArray);i++) 
    { 
     if(mainArray[i]==',') 
      count++; 
    } 
    /* Allocate the grid and tokezine */ 
    grid = malloc(sizeof(grid) * count); 
    grid[0] = strdup(strtok(mainArray,",")); 
    for(i=1;i<count;i++) 
    { 
     grid[i] = strdup(strtok(NULL,",")); 
    } 
    /* Display */ 
    for(i=0;i<count;i++) 
    { 
     printf("grid[%2d]:: %s\n",i,grid[i]); 
     free(grid[i]); /* free the malloc-ed string */ 
    } 
    free(grid); 
    fclose(fp); 
    return 0; 
} 

출력 : 나는 이미이 게시물에 댓글을 맹세 한 수 이상해

Width: 4, Height: 5 

Line:: 11,12,13,14, MainArray:: 11,12,13,14, 

Line:: 21,22,23,24, MainArray:: 11,12,13,14,21,22,23,24, 

Line:: 31,32,33,34, MainArray:: 11,12,13,14,21,22,23,24,31,32,33,34, 

Line:: 41,42,43,44, MainArray:: 
11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44, 

Line:: 51,52,53,54, MainArray:: 
11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44,51,52,53,54, 

Line:: 51,52,53,54, MainArray:: 
11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44,51,52,53,54,51,52,53,54, 

grid [ 0]:: 11 
grid [ 1]:: 12 
grid [ 2]:: 13 
grid [ 3]:: 14 
grid [ 4]:: 21 
grid [ 5]:: 22 
grid [ 6]:: 23 
grid [ 7]:: 24 
grid [ 8]:: 31 
grid [ 9]:: 32 
grid [10]:: 33 
grid [11]:: 34 
grid [12]:: 41 
grid [13]:: 42 
grid [14]:: 43 
grid [15]:: 44 
grid [16]:: 51 
grid [17]:: 52 
grid [18]:: 53 
grid [19]:: 54 
grid [20]:: 51 
grid [21]:: 52 
grid [22]:: 53 
grid [23]:: 54 
+0

. 어쨌든 ... 안녕 비나 야카! 도와 주셔서 감사합니다. 그것은 치료를 작동합니다 : D – mh4

+0

하지만 @BinayaChakraborty 비록 질문이 있습니다. 왜 strdup을 사용합니까? 그와 strcpy의 차이점은 무엇입니까? 나는 abt를 연구함으로써 이해하려고 노력했다. 그러나 그것이 정말로 "왜"(그것이 의미가 있는지)를 정말로 이해할 수는 없다. // 나머지 부분보다 나에게 더 의미가있는 부분입니다. [link] (http://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c) [link] (http://stackoverflow.com/questions/4079850/why- do-we-need-strdup) "s"(인수)를 가리키는 "문자열"의 복제본 인 새로운 "문자열"에 대한 char 포인터를 반환한다는 것을 이해하지만 왜 그런가? – mh4

+0

@ mh4 : 범위를 생각해보십시오. 나중에 문자열 포인터를 사용하려면 유효한 반환 주소를 사용해야합니다. 그렇지 않으면, SEGFAULT –

관련 문제