首页 文章

使用fgets并使用printf只打印一些行

提问于
浏览
0

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

我使用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

1 回答

  • 2

    如果你的输入文件表示是准确的,那么你有大约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);
    

    等等 .

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

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

    enum {//list all known elements of your file
        to,
        from,
        date,
        subject,
        max_lines
    }
    
    char header[max_lines][80];
    char body[SOME_LARGER_NUMBER];// hardcoded size not best approach, just for illustration.
    int i = 0;
    while(fgets(header[i], 80, fp))
    {
        if(strlen[header[i]) > 1) i++;  //increment lines index only when string has length > 1
    }
    

    获得头信息后,启动一个新的循环部分以连接正文文本 .

相关问题