Originally Posted by
grumpy
Mindreading is not a common skill among forum members. You might want to read
this link before posting again.
What data is being input? What is being output?
You may see nothing wrong with your code. I see multiple problems. I'll give a hint about two significant categories of error your code exhibits (multiple times).
Why isn't your code checking whether operations (opening files, reading data, writing data, etc) are succeeding? In your code, if any operation fails, most subsequent operations will also fail. Failing to open a file prevents any input or output operations on that file. Failure to read data will mean subsequent output of that data will not be as expected.
Your code opens the file "product.txt" twice (once for writing, once for reading). It is never closed. A file has to be closed before it can be reopened (unless some means of file sharing is active, which your code hasn't activated.
Thanks, i'll keep that in mind. btw, this is just a prototype of my code so i haven't added the codes to check for succeeded operations. I have followed your hints and got the code to work, however, i had another problem. Could you take a look at this for me? Why can't I get the sort function to work
Code:
#include<stdio.h>
typedef struct prd
{
char name[30];
char code[30];
char idt[30];
float price;
}prd,temp;
void write();
void sort();
int i,j;
void searchcode();
void searchname();
int main()
{FILE *f;
f=fopen("product.txt","w");
printf("Input number of products: ");scanf("%d",&i);
struct prd product[i];
printf("Please input information of these products");
for (j = 0;j<i;j++)
{
printf("\nProduct #%d:\n",j+1);
printf("Name:");
scanf("%s",product[j].name);
printf("Code:");
scanf("%s",product[j].code);
printf("Id:");
scanf("%s",product[j].idt);
printf("Price:");
scanf("%f", &product[j].price);
}
fprintf(f,"NAME\tCODE\tID\tPRICE\n");
for (j = 0;j<i;j++)
{
fprintf(f,"%s\t",product[j].name);
fprintf(f,"%s\t", product[j].code);
fprintf(f,"%s\t", product[j].idt);
fprintf(f,"%0.2f\n", product[j].price);
}
fclose(f);
sort();
}
void sort()
{
FILE *f;
int k;
char line[500];
f=fopen("product.txt","r+");
prd product[i];
fscanf(f,"%[^\n]\n",line);
for(j=0;j<i;j++)
{
fscanf(f,"%s %s %s %f",product[j].name,product[j].code,product[j].idt,&product[j].price);}
printf("name %s\n",product[j].name);
for (j=0;j<i-1;j++)
{
for (k=j+1;k<i;k++)
{
if (product[j].price<product[k].price)
{
struct prd temp=product[j];
product[j]=product[k];
product[k]=temp;
}}}
for (j=0;j<i;j++)
{
fprintf(f,"%s\t",product[j].name);
fprintf(f,"%s\t", product[j].code);
fprintf(f,"%s\t", product[j].idt);
fprintf(f,"%0.2f\n", product[j].price);}
fclose(f);
getch();
}