-2
我已經設法制作一個程序,可以從一個文件中編輯一行表格。 但問題是,每當我輸入的最後一行的數字以編輯,它使我的程序崩潰...作了一個程序來編輯行
這是文本文件,我用它來編輯....
***** INVENTORY *****
-------------------------------------------------------------------------
S.N. | NAME | CODE | QUANTITY | PRICE
-------------------------------------------------------------------------
1 25 45 54 54.00
2 fkfgyl 55dtylk2d 52 54.25
2 fkfgyl 55dtylk2d 52 54.25
2 fkfgyl 55dtylk2d 52 54.25
5 kjbx zkjhvkz 45 45.00
2 fkfgyl 55dtylk2d 52 54.25
2 fkfgyl 55dtylk2d 52 54.25
2 fkfgyl 55dtylk2d 52 54.25
2 fkfgyl 55dtylk2d 52 54.25
2 kj 5j; 2 5.00
2 fkfgyl 55dtylk2d 52 54.25
看!每當我輸入11(表示第15行),程序就會凍結!
這是代碼:
#include <stdio.h>
FILE *fileptr1, *fileptr2;
int adddata(i);
int main(void)
{
char c;
int delete_line, temp = 1;
fileptr1 = fopen("inventory.txt", "r");
c = getc(fileptr1);
//print the contents of file .
while (c != EOF)
{
printf("%c", c);
c = getc(fileptr1);
}
printf("\n\n\n Enter S.N. to be deleted and replaced ");
scanf("%d", &delete_line);
delete_line = delete_line+4;
//take fileptr1 to start point.
rewind(fileptr1);
//open replica.c in write mode
fileptr2 = fopen("replica.c", "w");
c = getc(fileptr1);
while (c != EOF)
{
if (c == '\n')
{
temp++;
}
//till the line to be deleted comes,copy the content to other
if (temp != delete_line)
{
putc(c, fileptr2);
}
else
{
while ((c = getc(fileptr1)) != '\n')
{
}
fclose(fileptr2);
adddata(delete_line);
temp++;
fileptr2 = fopen("replica.c", "a");
fflush(stdin);
putc('\n', fileptr2);
}
//continue this till EOF is encountered
c = getc(fileptr1);
}
fclose(fileptr1);
fclose(fileptr2);
remove("inventory.txt");
rename("replica.c", "inventory.txt");
fileptr1 = fopen("inventory.txt", "r");
//reads the character from file
c = getc(fileptr1);
//until last character of file is encountered
while (c != EOF)
{
printf("%c", c);
//all characters are printed
c = getc(fileptr1);
}
fclose(fileptr1);
return 0;
}
int adddata(i) {
fileptr2 = fopen("replica.c", "a");
struct details
{
char name[20];
char code[20];
float price;
long int quantity;
};
struct details item[1];
fflush(stdin);
printf("\nItem name: ");
scanf("%s", &item[0].name);
item[0].name[19] = '\0';
fflush(stdin);
printf("\nItem code: ");
scanf("%s", &item[0].code);
item[0].code[19] = '\0';
fflush(stdin);
printf("\nItem price: ");
scanf("%f", &item[0].price);
fflush(stdin);
printf("\nItem quantity: ");
scanf("%8ld", &item[0].quantity);
fflush(stdin);
fprintf(fileptr2, "\n %3d %-20s %-20s %-8ld %9.2f ", i-4, item[0].name, item[0].code, item[0].quantity, item[0].price);
fclose(fileptr2);
return 0;
}
我建議生成一個仍然顯示錯誤行爲的最小程序。這會讓別人更容易幫助你。 – cjubb39 2014-09-22 22:24:05
你當然不應該叫'fflush(stdin)'。 – 2014-09-22 22:26:26
爲什麼我不應該叫fflush(stdin)? 我還能做什麼? 我是一名新手......剛開始學習編程幾天:( – Ibrahim 2014-09-22 22:50:45