2016-09-06 2 views
-4

함수는 양의 정수 (한 줄에 하나씩)를 포함하는 입력 파일을 읽고 셀 당 하나씩이 숫자를 포함하는 목록을 만듭니다. 입력 파일의 -1은 목록의 끝을 나타냅니다. 이렇게하면 동일한 입력 파일에 여러 개의 목록을 지정할 수 있습니다. 입력 파일을 "입력"이라고 가정합니다. 함수를 호출 할 때마다 -1에 도달 할 때까지 입력 파일의 숫자를 읽고이 숫자를 목록에 넣고이 목록의 머리글에 대한 포인터를 반환합니다. 따라서 입력 파일에 1 5 4 -1 4 8 6 -1 -1 7 8 이 포함 된 경우 함수에 대한 첫 번째 호출은 1-> 5-> 4-> null에 대한 포인터를 반환하고 두 번째 호출은 함수는 4 -> 8 -> 6-> null 목록에 대한 포인터를 리턴합니다. 세 번째 호출은 null을 반환하고 네 번째 호출은 7-> 8-> null을 반환합니다. 이것을 달성하고 싶었습니다. 지금까지 텍스트 파일에서 파일을 읽을 수있었습니다. 이제 -1에 도달 한 지느러미 파일마다 -1까지 번호를 받아 목록을 만들어야했습니다. 이 같은리스트 만들기

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

struct list { 
    char *string; 
    struct list *next; 
}; 

typedef struct list LIST; 

int main() { 
    FILE *fp; 
    char line[128]; 
    LIST *current, *head; 

    head = current = NULL; 
    fp = fopen("test.txt", "r"); 

    while (fgets(line, sizeof(line), fp)) { 
     LIST *node = (struct list *)malloc(sizeof(LIST)); 
     node->string = _strdup(line);// strdup(line);//note : strdup is not standard function 
     node->next = NULL; 

     if (head == NULL) { 
      current = head = node; 
     } 
     else { 
      current = current->next = node; 
     } 
    } 
    fclose(fp); 
    //test print 
    for (current = head; current; current = current->next) { 
     printf("%s", current->string); 
    } 
    //need free for each node 
    return 0; 
} 
+2

나는 거기에 질문을 확인할 수 없습니다. – EOF

+0

여기 어딘가에 질문이 있습니까? – saarrrr

+0

각 목록을 목록의 목록에 저장합니까? – BLUEPIXY

답변

0

:

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

struct list { 
    int v; 
    struct list *next; 
}; 

typedef struct list LIST; 

LIST *makeListFromFile(FILE *fp){ 
    int v; 
    LIST *current, *head = NULL; 

    while(fscanf(fp, "%d", &v) == 1 && v != -1){ 
     LIST *node = malloc(sizeof(LIST)); 
     node->v = v; 
     node->next = NULL; 
     if (head == NULL) 
      current = head = node; 
     else 
      current = current->next = node; 
    } 
    return head; 
} 

int main(void) { 
    FILE *fp = fopen("test.txt", "r"); 

    while(!feof(fp)){ 
     LIST *list = makeListFromFile(fp); 
     while(list){ 
      LIST *temp = list->next; 
      printf("%d ", list->v); 
      free(list); 
      list = temp; 
     } 
     puts("NULL"); 
    } 
    fclose(fp); 
    return 0; 
}