所以对于我的一个类,我必须用c创建一个.txt文件,然后删除其中的几行。
创建功能进行顺利的任何方式,但删除功能只工作后,我单独创建文件,然后删除,而创建功能变成了一个注解(又名它只工作时,我删除行关闭一个文件,已经创建前执行)
有没有办法让它们同时工作?
ps:idk如果这是一个明显的问题,一个非初学者
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 256
typedef struct a
{
int quan, num, price;
char name[100];
} ar;
ar art;
void ajt(int n)
{
int i;
FILE *f = fopen("stock.txt", "w");
if (f == NULL)
return;
for (i = 1; i <= n; i++)
{
printf("name of the product n* %d: ", i);
scanf("%s", &art.name);
fprintf(f, "name of the product n* %d is: %s ", i, art.name);
printf("number of the product n* %d: ", i);
scanf("%d", &art.num);
fprintf(f, "number of the product n* %d is: %d ", i, art.num);
printf("quantity of the product n* %d: ", i);
scanf("%d", &art.quan);
fprintf(f, "quantity of the product n* %d is: %d ", i, art.quan);
printf("price of the product n* %d:", i);
scanf("%d", &art.price);
fprintf(f, "price of the product n* %d is: %d \n", i, art.price);
printf("\n\n");
}
}
void del()
{
FILE *fileptr1, *fileptr2;
char filename[40];
char ch;
int delete_line, temp = 1;
printf("the name of your file: ");
scanf("%s", filename);
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
rewind(fileptr1);
printf("which product do u want to delete? ");
scanf("%d", &delete_line);
fileptr2 = fopen("copy.c", "w");
ch = getc(fileptr1);
while (ch != EOF)
{
ch = getc(fileptr1);
if (ch == '\n')
temp++;
if (temp != delete_line)
{
putc(ch, fileptr2);
}
}
fclose(fileptr1);
fclose(fileptr2);
remove(filename);
rename("copy.c", filename);
printf("\n the text file after modifications:\n");
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
fclose(fileptr1);
}
int main()
{
int n;
printf("how many products: ");
scanf("%d", &n);
printf("\n\n");
ajt(n);
del();
}
1条答案
按热度按时间5f0d552i1#
在创建文件后关闭它,或者调用
fflush(f);
将流缓冲区刷新到文件系统。它没有被写入文件系统,所以文件还不包含数据,所以打开一个单独的流不能读取或改变数据。