[英]fgets() not saving the first line in c
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. 在data_f中打印数据可以正常工作,但是当我使用fseek将指针移动到文件的开头并扫描一行时,它将扫描最后一行并存储在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? 我期望fgets存储data_f的第一行,但存储最后一行,为什么?
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. 以“ w +”模式打开文件以允许同时进行读取和写入。
You can read more on fopen(3) here: https://linux.die.net/man/3/fopen 您可以在这里阅读有关fopen(3)的更多信息: https : //linux.die.net/man/3/fopen
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.