Reputation: 95
I am trying to remove a line from a file at load time.
Printing data in data_f works fine but when I use fseek to move pointer to the beginning of file and scan a line, it scans the last line and stores in s.
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
FILE *fp1 = fopen("data_f", "w");
FILE *fp = fopen(argv[1], "r");
char s[100];
int c=1, chk = atoi(argv[2]);
while(fgets(s, 100, fp)) //counting number of lines
{
if(c != chk)
fputs(s, fp1);
c++;
}
fseek(fp1, 0, SEEK_SET);
fgets(s, 100, fp1);
printf("%s\n", s);
}
I was expecting fgets to store first line of data_f but it stores last line, why?
Upvotes: 0
Views: 118
Reputation: 326
You are trying to read from a file that was opened in write only mode.
FILE *fp1 = fopen("data_f", "w");
.
.
.
fgets(s, 100, fp1);
Open the file in "w+" mode to allow both read&write.
You can read more on fopen(3) here: https://linux.die.net/man/3/fopen
Upvotes: 1