2014-04-21 2 views
0

텍스트 파일에서 데이터를 가져 와서 구조체에 넣을 수있는 프로그램을 작성하려고하면 연결된 목록에 구조체를 추가 한 다음 나중에 목록을 표시합니다. 배열이 없습니다. 현재 목록을 표시하려고 할 때 구조체의 각 필드에 줄 바꿈을 읽는 데 문제가 있습니다. 잘못된 값/횡설수설을줍니다. 제가 중점적으로 다루는 부분은 기본 방법입니다. 구조체로 텍스트 파일 읽기

내가 읽으려고하고있는 텍스트 파일입니다

#1 Flat Blade Screwdriver 
12489 
36 
.65 
1.75 
#2 Flat Blade Screwdriver 
12488 
24 
.70 
1.85 
#1 Phillips Screwdriver 
12456 
27 
0.67 
1.80 
#2 Phillips Screwdriver 
12455 
17 
0.81 
2.00 
Claw Hammer 
03448 
14 
3.27 
4.89 
Tack Hammer 
03442 
9 
3.55 
5.27 
Cross Cut Saw 
07224 
6 
6.97 
8.25 
Rip Saw 
07228 
5 
6.48 
7.99 
6" Adjustable Wrench 
06526 
11 
3.21 
4.50 

을이 지금까지 내 프로그램입니다 :

#include "stdafx.h" 
#include <stdio.h> 
#include <stdlib.h> 
#include <stddef.h> 

typedef struct inventory 
{ 
    char invName[36]; 
    int invPartNo; 
    int invQOH; 
    float invUnitCost; 
    float invPrice; 
}stock; 

struct NODE 
{ 
    union 
    { 
     int nodeCounter; 
     void *dataitem; 
    }item; 
    struct NODE *link; 
}; 

struct NODE *InitList(); 
void DisplayNode(struct inventory *); 
struct inventory * ReadData(FILE *); 
void DisplayList(struct NODE *); 
struct NODE* GetNode(FILE *); 
void Add2List(struct NODE *, struct NODE *); 
struct NODE* SearchList(struct NODE *, int); 
void DeleteNode(struct NODE *, int); 


int main(int argc, char* argv[]) 
{ 
    struct NODE *header; 
    header = InitList(); 
    char line[50]; 

    int i, j; 
    i = 0; 
    FILE *fp = fopen("input.txt", "r"); 
    if(fp != NULL) 
    { 
     while(fgets(line, sizeof(line), fp)) 
     { 
      struct NODE *nNode = (struct NODE*)malloc(sizeof NODE); 
      struct inventory *newNode = (struct inventory*)malloc(sizeof inventory); 
      fscanf(fp,"%s %d %d %f %f ", newNode->invName, &newNode->invPartNo,&newNode->invQOH,&newNode->invUnitCost,&newNode->invPrice); 

      /* 
      fscanf(fp, "%s", newNod->invName); 
      fscanf(fp, "%d", newNod->invPartNo); 
      fscanf(fp, "%d", newNod->invQOH); 
      fscanf(fp, "%f", newNod->invUnitCost); 
      fscanf(fp, "%f", newNod->invPrice); 
      */ 

      nNode->item.dataitem = newNode; 
      nNode->item.nodeCounter++; 
      Add2List(header, nNode); 
     } 
    } 
    DisplayList(header); 

    //startNode->invName = array[0].invName; 
    //struct inventory *startNode; 

    /* 
    char line[BUFSIZ]; 
    while (fgets(line, sizeof line, fp) != NULL && sscanf(line, " %s %d %11s %19s %lf", &record.empNum, record.firstName, record.lastName, &record.hourRate) == 4) 
    { 

    }*/ 

    /* 
    struct NODE *header; 
    header = InitList(); 

    int PCounter = 2; 
    while (PCounter--) 
    { 
     Add2List(header,GetNode(stdin)); 
    } 

    DisplayList(header); 
    */ 

    return 0; 
} 

struct NODE *InitList() 
{ 
    struct NODE *temp = (struct NODE*)malloc(sizeof NODE); 

    temp->item.nodeCounter = 0; 
    temp->link = NULL; 
    return temp; 
} 


void Add2List(struct NODE *start, struct NODE *NewNode) 
{ 
    struct NODE *current = start; 

    while (current->link != NULL) 
     current = current->link; 

    current->link = NewNode; 
    NewNode->link = NULL; 

    start->item.nodeCounter++; 
} 


struct NODE* GetNode(FILE *fptr) 
{ 
    struct NODE *temp = (struct NODE*)malloc(sizeof NODE); 

    temp->item.dataitem = ReadData(fptr); 
    temp->link = NULL; 

    return temp; 
} 


void DisplayList(struct NODE *start) 
{ 
    struct NODE *current = start->link; 

    while (current != NULL) 
    { 
     DisplayNode((struct inventory *)current->item.dataitem); 
     current = current->link; 

    } 
} 


void DisplayNode(struct inventory *stuff) 
{ 
    printf("Name: %s", stuff->invName); 
    printf("Part Number: %d", stuff->invPartNo); 
    printf("Quantity on hand: %d", stuff->invQOH); 
    printf("Unit Cost: %0.2f", stuff->invUnitCost); 
    printf("Price %0.2f", stuff->invPrice); 
} 


struct inventory * ReadData(FILE *fptr) 
{ 
    struct inventory *temp = (struct inventory *)malloc(sizeof inventory); 

    if(fptr==stdin) 
     printf("Enter item name: "); 
    fscanf_s(fptr, "%s", temp->invName); 
    if(fptr==stdin) 
     printf("Enter item part number: "); 
    fscanf_s(fptr, "%d", &temp->invPartNo); 
    if(fptr==stdin) 
     printf("Enter item quantity on hand: "); 
    fscanf_s(fptr, "%d", &temp->invQOH); 
    if(fptr==stdin) 
     printf("Enter item unit cost: "); 
    fscanf_s(fptr, "%f", &temp->invUnitCost); 
    if(fptr==stdin) 
     printf("Enter item price: "); 
    fscanf_s(fptr, "%f", &temp->invPrice); 

    return temp; 
} 

struct NODE* SearchList(struct NODE *start, int oldData) 
{ 
    struct NODE* current = start; 
    struct inventory * st = (struct inventory *)current->link->item.dataitem; 

    while (st->invPartNo != oldData && current != NULL) 
    { 
     current = current->link; 
     if(current->link) 
      st = (struct inventory *)current->link->item.dataitem; 
    } 
    return current; 
} 

void DeleteNode(struct NODE *start, int oldData) 
{ 
    struct NODE *current, *oldNode; 

    current = SearchList(start, oldData); 
    oldNode = current->link; 
    current->link = oldNode->link; 
    free(oldNode); 
    start->item.nodeCounter -= 1; 
} 


struct inventory* readFromFile() 
{ 
    /* 
    FILE *fp; 
    fp = fopen("input.txt", "r"); 
    struct inventory *header, *temp; 
    //header = InitList(); 

    char invName[36]; 
    int invPartNo; 
    int invQOH; 
    float invUnitCost; 
    float invPrice; 

    fscanf(fp, "%s", temp->invName); 
    fscanf(fp, "%d", &temp->invPartNo); 
    fscanf(fp, "%d", &temp->invQOH); 
    fscanf(fp, "%f", &temp->invUnitCost); 
    fscanf(fp, "%f", &temp->invPrice); 
    fclose(fp); 
    */ 

    /* 
    char invName[36]; 
    int invPartNo; 
    int invQOH; 
    float invUnitCost; 
    float invPrice; 

    //--------------------------------------------------------------- 
    char ch, file_name[100]; 
    FILE *fp; 
    printf("Enter the name of file you wish to see\n"); 
    gets(file_name); 
    fp = fopen(file_name,"r"); // read mode 
    if(fp == NULL) 
    { 
     perror("Error while opening the file.\n"); 
     exit(EXIT_FAILURE); 
    } 
//--------------------------------------------------------------- 
    int i = 0; 
    //while((ch = fgetc(fp)) != EOF) 
    //while(!feof(fp)) 
    while((ch != '\n') && (ch != EOF)) 
    { 
     struct inventory *temp; 
     char *fgets(temp->invName, 100, fp); 
     fscanf(fp, "%d", &temp->invPartNo); 
     fscanf(fp, "%d", &temp->invQOH); 
     fscanf(fp, "%f", &temp->invUnitCost); 
     fscanf(fp, "%f", &temp->invPrice); 
    }*/ 
    return 0; 
} 

void readFile() 
{ 
    stock array[20]; //9 items to read from list 
    int i, j; 
    i = 0; 
    FILE *fp = fopen("input.txt", "r"); 
    if(fp != NULL) 
    { 
     while(fgets(array[i].invName, sizeof array[i].invName, fp)) 
     { 
      fscanf(fp,"%d %d %f %f ",&array[i].invPartNo,&array[i].invQOH,&array[i].invUnitCost,&array[i].invPrice); 
      i++; 
     } 
    } 

} 
+1

정확한 문제가 무엇 그대로 루프의 나머지 부분을 떠날 수 있을까? – Alex

+0

프로그램을 실행할 때 구조체에 잘못된 값이 걸리므로 표시 할 때 구조체 내용에 대해 완전히 잘못된 값이 인쇄됩니다. – user3011161

답변

0

당신은 fgets와 라인을 읽은 다음 구조체를 읽으려고 fscanf. fgets이 이미 줄을 먹었으므로 fscanf을 실행하면이 기능이 작동하지 않습니다. 귀하의 코드는 다음과 같을 수 있습니다

입력을 저장하거나 처리 할 때 나중에 사용할 수있는 임시 버퍼로 입력을 읽습니다.

업데이트 :

또 다른 방법 EOF를 테스트하고

while(!feof(fp)) { 
    struct NODE *nNode = (struct NODE*)malloc(sizeof NODE); 
    struct inventory *newNode = (struct inventory*)malloc(sizeof inventory); 
    fscanf(fp, "%s %d %d %f %f ", newNode->invName, &newNode->invPartNo, &newNode->invQOH, &newNode->invUnitCost, &newNode->invPrice); 
    nNode->item.dataitem = newNode; 
    nNode->item.nodeCounter++; 
    Add2List(header, nNode); 
} 
+0

나는 이것을 사용하기 위해 코드를 변경하려고 시도했지만, 지금은 아무것도 읽지 않는다. 조금 더 확장 할 수 있을까요? – user3011161

+0

업데이트 된 답변을 참조하십시오. –

+0

두 번째 방법은 나를 위해 반으로 작동합니다. 그러나 오류가 줄 끝에서 \ n을 읽음으로 인해 발생하는 것 같습니다. 어떻게 해결할 수 있습니까? – user3011161