【问题标题】:Using fgets and using printf only some lines are printed使用 fgets 和使用 printf 只打印一些行
【发布时间】:2017-02-05 18:29:58
【问题描述】:

我正在尝试编写一个给定一些文本文件的函数,它会返回一些特定的行。但问题是其中一些没有打印出来。

我使用 fgets(var, 1500,(file*)fp) 从文件中获取每一行,然后使用 printf 打印它。

文件的内容是这样的:

收件人:马克

发件人:鲍勃

ID:0

2017 年 2 月 5 日星期日 13:21:38

主题:足球

文字:下周六早上

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

 void listmails(){


 char To[300];
 char From[300];
 char Date[1500];
 char Subject[300];
 char ID[300];
 char Text[300];
 char llegible[500];
 int countkong = 0;

  FILE *fp;


 while (countkong != -1 ){
 sprintf(llegible, "%d_EDA1_email.txt", countkong); // files name  are of the type 0_EDA1_email.txt, 1_EDA1_email.txt...

 fp = fopen(llegible, "r");
 countkong ++;
 if(fp!=NULL){



       fgets(To, 300, (FILE*)fp); // I don't want to do nothing wit this line, only to jump to the next line of the file

       fgets(From, 300, (FILE*)fp);
       printf("%s\n", From);
       fgets(ID, 300, (FILE*)fp);
       printf("%s\n", ID);
       fgets(Date, 1500, (FILE*)fp);
       fgets(Subject, 300, (FILE*)fp);
       printf("%s\n", Subject);

        }

    }

}


int main()
{

listmails();
return 0;

}

this is what I get

【问题讨论】:

  • 请包含完整且可编译的代码段,以及格式以便于阅读。对于初学者,您不需要在参数列表中输入fp。只要在您致电fopen();(您没有验证)之后存在fpfgets(From, 300, fp); 就可以正常工作。最后,指向结果的链接应替换为代码段下的简单文本描述。
  • 请在您的问题中包含文本输出作为文本(代码 - 缩进)。不要链接到图片。

标签: c netbeans printf


【解决方案1】:

如果您的输入文件表示是准确的,那么您大约有 11 或 12 行,其中一些带有可见文本,其他只有空白,可能是一个新行 (\n)

fgets()

C 库函数 char *fgets(char *str, int n, FILE *stream) 从指定的流中读取一行并将其存储到字符串中 由str指向。它在读取任何 (n-1) 个字符时停止, 读取换行符或到达文件结尾,以两者为准 先到先得。
...
成功时,该函数返回相同的 str 参数。如果 遇到文件结尾且未读取任何字符,则 str 的内容保持不变,返回一个空指针。

如所写,您的代码似乎可以读取一些内容,而不是您认为它正在读取的内容:

  fgets(From, 300, (FILE*)fp);  //reads "To: Mark"
   printf("%s\n", From);
   fgets(ID, 300, (FILE*)fp);  //reads "\n"
   printf("%s\n", ID); 

等等。

但是,从查看您的结果来看,我不确定您在代码段中包含的内容实际上是您编译的内容。

要改进,请尝试使用循环结构来读取您的文件:

//to avoid using magic numbers in code, define a line length
#define LINE_LEN (80)

enum {//list all known elements of your file
    to,
    from,
    date,
    subject,
    max_lines
}

char header[max_lines][LINE_LEN];
char body[SOME_LARGER_NUMBER];// hardcoded size not best approach, just for illustration.
int i = 0;
while(fgets(header[i], LINE_LEN, fp))
{
    if(strlen[header[i]) > 1) i++;  //increment lines index only when string has length > 1
}

获得标题信息后,开始一个新的循环部分以连接正文。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    相关资源
    最近更新 更多