打印到文本文件时出错

时间:2013-12-21 05:27:35

标签: c

我的代码下面有函数read()的问题我想。函数input()没问题,但是当我使用函数read()进行排序时,文本文件的内容会出错。有人可以帮我解释一下吗?感谢

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

void input();
void menu();
void read();

struct product{
    char code[20];
    char name[50];
    int quan;
    float pr;
} ;

void menu()
{

    int k;
    printf("___________MENU________\n");
    printf("1. Enter the info of your products which is saved in Products.txt\n");
    printf("2. Read the file Products.txt & sort by price.\n");
    printf("3. Exit");
    printf("________________________\n");
    printf("Enter your option: ");
    fflush(stdin);
    scanf("%d", &k);

    switch(k){
case 1:
    input();
    break;
case 2:
    read();
    break;
case 3:
    printf("\nTerminating");
    exit(0);
    break;
default:
    printf("\nError!Please Try Again\n");
    break;
};
}


void input()
{
struct product proinfo[50];
FILE *fp;
int i,n;



if((fp = fopen("Products.txt", "wt")) == NULL) 
  { 
    printf("Error opening file!\n"); 
    exit(0); 
  } 

fprintf(fp,"Code - Name - Quantity - Price (million)\n\n");  
printf("How many products: ");
scanf("%d", &n)
for(i = 0; i < n; i++) 
{ 
    printf("Code of product # %d: ", i + 1); 
    fflush(stdin);
    gets(proinfo[i].code);
    fflush(stdin);  
    printf("Name: "); 
    gets(proinfo[i].name);
    printf("Quantity: ");
    scanf("%d", &proinfo[i].quan);
    printf("Price: ");
    scanf("%f", &proinfo[i].pr); 

} 

if(fp != NULL)
    {
    for(i = 0 ; i < n ; i++)
        fprintf(fp,"%s - %s - %d - %.2f \n", proinfo[i].code, proinfo[i].name, proinfo[i].quan, proinfo[i].pr);
        fclose(fp);
    }

printf("Saving Succesfully");
fflush(stdin);
}


void read()
{
struct product proinfo[50], temp;
int i, j, n;

FILE *fp;
fp=fopen("Products.txt", "w+t");

fprintf(fp,"Code - Name - Quantity - Price (million)\n\n"); 

printf("How many products again: ");
scanf("%d", &n);

    for(i=0;i<n-1;i++)
    {
        for(j=i+1;j<n;j++)
        {
        if(proinfo[i].pr<proinfo[j].pr)
        {
            temp=proinfo[i];
            proinfo[i]=proinfo[j];
            proinfo[j]=temp;
        }       
        }
    }
    //saved into file
    for(i=0; i < n; i++)
    {
        fprintf(fp, "%s - %s - %d - %f \n", proinfo[i].code, proinfo[i].name, proinfo[i].quan, proinfo[i].pr);
    }

fclose(fp); 
}   

int main(void)
{
int a;
for(a=0;;a++)
{
    menu();
    getch();    
}
}

1 个答案:

答案 0 :(得分:0)

2 struct product proinfo[50]是函数input()read()中的单独局部变量。

input()填写一个,看起来OP希望read()中存在相同的值。 (或者至少需要从文件中读取它。)

需要将struct product proinfo[50]全局(yeech)或作为函数参数传递。