gpt4 book ai didi

c - 读取文件特定部分时出现问题

转载 作者:行者123 更新时间:2023-11-30 20:20:09 25 4
gpt4 key购买 nike

我试图在给定时间从文件中提取并打印文本的特定部分。我使用 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

我想打印要打印的两行。请建议一种方法。

最佳答案

我认为您阅读部分的意图是

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+1];

int used = 0;
while(ftell(fp) < b)
{
fgets(x+used, sizeof(x)-used, fp);
used = strlen(x);
}
printf("%s", x);

注释:

  • 我在缓冲区 x 的分配中添加了 +1,因为 fgets 添加了空终止。

  • 我不能 100% 确定您不希望在写入和读取之间使用 fflush(fp)

关于c - 读取文件特定部分时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47387953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com