2014-06-24 2 views
-1

순차 액세스 파일에 새 레코드를 추가하는 데 문제가 있습니다. 사용자가 모델 코드를 입력하면 프로그램은이를 확인하고 중복이 발견 된 경우 동일한 이름의 항목이 이미 있음을 표시합니다. 내 코드를 실행하면, 그냥 보여줍니다 때c 프로그램. 텍스트 파일에 레코드 추가시 문제가 발생합니다.

Record already exists 
Record already exists 
Record already exists 
Record already exists 

가 : 1. 코드가 파일에 존재 2. 코드가 파일에 존재하지 않습니다.

누군가 나를 도와 줄 수 있습니까? 어떤 도움을 주시면 감사하겠습니다.

//function to add record 
void stockEntry(){ 

    FILE *fp; 
    fp = fopen("stock.txt","a+"); 

    //fopen opens file.Exit program if unable to create file 
    if(fp==NULL){ 
     puts("File could not be opened"); 
    }//ends if 

    //obtains information from user 
    else{   
     printf("\nEnter model code,model name,cost,price and quantity(Use space to separate inputs)\n"); 
     scanf("%s %s %f %f %d",code,a.name,&a.cost,&a.price,&a.quantity); 

     rewind (fp); 
     do{ 
      if(strcmp(code,a.code)!=0){  
       //write details into stock.txt 
       fprintf(fp,"%s %s %.2f %.2f %d\n",a.code,a.name,a.cost,a.price,a.quantity); 
      } 
      else{ 
       printf("Record already exists\n"); 
      } 

     }while(fscanf(fp,"%s %s %f %f %d\n",a.code,a.name,&a.cost,&a.price,&a.quantity)==5); 
    } 
    //fclose closes file 
    fclose(fp); 
} 
+1

어디'code'하고있는'A' 초기화/선언과 그 유형은 무엇입니까? – simonc

+0

코드는 본체 전에 선언됩니다 – user3676752

+0

은 구조체 배열의 이름이며 본체 전에 초기화되었습니다 – user3676752

답변

0

당신은 아무것도 파일에서 읽은 전에 데이터를 비교하는 것이다하는 do...while 루프를 사용하고, 첫 번째로는 의 이전 값과 비교하면 입니다. 또한 파일의 가운데에있는 에 데이터를 쓰고 있으며 모든 레코드가 동일한 길이라는 보장이 없습니다.

또한 사용자가받은 데이터를 모두 보유하려면 a을 사용하고 파일에서 읽은 데이터는 입니다. 각각 목적을 위해 하나씩 두 개의 구조가 필요합니다.

왜 항상 당신에게 Record already exists을 줄지 모르겠지만 루프 은 원하는 결과를 제공해야합니다. (I 컴파일하지 않았거나 시험은, 이것은 단지 내 머리 위로 떨어져있다.)

int exists; 
struct ... curr; 
... 
scanf("%s %s %f %f %d", curr.code, curr.name, &(curr.cost), 
     &(curr.price), &(curr.quantity)); 

exists = 0; 
rewind(fp); 

while (fscanf(fp, "%s %s %f %f %d\n", 
     a.code, a.name, &(a.cost), &(a.price), &(a.quantity)) == 5) { 
    if (strcmp(curr.code, a.code) == 0) { 
     printf("Record already exists\n"); 
     exists = 1; 
     break; 
    } 
} 

/* At this point, either exists == 1, in which case we're at an unknown 
    point in the file and wish to do nothing, or exists == 0, in which 
    case we're at the end of the file and wish to write a new record. */ 

if (exists) 
    fprintf(fp, "%s %s %.2f %.2f %d\n", 
      curr.code, curr.name, curr.cost, curr.price, curr.quantity); 
+0

도움을 주셔서 감사합니다. 이제 작동합니다. – user3676752

+0

다행입니다. 나는 당신에게'정보 '배지가 없다는 것을 알았습니다. [둘러보기] (http://stackoverflow.com/tour)를 통해이 돈을 벌 수 있습니다.이 사이트에서는 사이트 사용 방법에 대해 많은 것을 설명합니다. –

+0

에서 확인해 보겠습니다. 다시 한 번 감사드립니다. – user3676752

관련 문제