so for one of my classes, I have to create a .txt file in c and then delete a few lines off of it. I wrote a separate function for each of these operations.
the creation function goes smoothly either way but the delete function only works after I separately create the file AND THEN delete while the the creation function is turned into a comment (aka it only works when I delete lines off a file that was already created before execution)
is there a way to make them both work at the same time?
ps: idk if this is an obvious question for a non-beginner
#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();
}
CodePudding user response:
Either close the file after creating it or call fflush(f);
to flush the stream buffer to the file system. If you do not do that, data remains in memory in the process; it is not written to the file system. So the file does not contain the data yet, so opening a separate stream to it cannot read or change that data.