【发布时间】:2017-11-20 08:40:22
【问题描述】:
我正在尝试在给定时间从文件中提取和打印特定部分的文本。我使用 ftell() 和 fseek() 来实现这一点。
#include <stdio.h> //// include required header files
#include <string.h>
int main()
{
FILE *fp = fopen("myt", "w+");
if (fp == NULL) //// test if file has been opened sucessfully
{
printf("Can't open file\n");
return 1; //// return 1 in case of failure
}
char s[80];
printf("\nEnter a few lines of text:\n");
while (strlen(gets(s)) > 0) //user inputs random data
{ //till enter is pressed
fputs(s, fp);
fputs("\n", fp);
}
long int a = ftell(fp);
fputs("this line is supposed to be printed only ", fp);//line to be
// displayed
fputs("\n", fp);
fputs("this line is also to be printed\n",fp); //line to be
//displayed
fputs("\n",fp);
long int b = ftell(fp);
fputs("this is scrap line",fp);
fputs("\n",fp);
rewind(fp);
fseek(fp, a, SEEK_CUR); //move to the starting position of text to be
//displayed
long int c=b-a; //no of characters to be read
char x[c];
fgets(x, sizeof(x), fp);
printf("%s", x);
fclose(fp);
return 0; //// return 0 in case of success, no one
}
我尝试使用这种方法,但程序只打印第一行。输出如下:
this line is supposed to be printed only
我想打印要打印的两行。请提出一种方法。
【问题讨论】:
-
fgets()读取一行(在换行处停止)。要么多次调用fgets(),要么只使用fread()读取给定数量的数据。 -
由于这与您的实际问题无关,因此我投票将其作为“简单的错字”结束。
-
有人可以帮我写一段代码吗?我是新手,需要帮助
-
+Felix Palmen 我已更正标题。请撤下您的投票
-
我刚刚向您解释了您的问题是什么,这是对
fgets()的错误假设。同样,fgets()在第一个换行符处停止阅读。你还需要什么来解决这个问题? :o
标签: c arrays fopen file-handling fseek