简体   繁体   English

我怎么知道fgets读取的单词是否在新行中?

[英]how would I know if the word being read by fgets is in a new line?

I'm reading a program in C and I want to locate the new line, but i don't know how. 我正在用C阅读程序,我想找到新行,但是我不知道如何。

I'm reading the text file like this: 我正在读取这样的文本文件:

    while(!feof(fp)){
         fgets(buffer, 4, fp);
    }

and my text file is like this: 我的文本文件是这样的:

C01 RDA ALB NAC EDF
C02 MCA EDF SLF ADG

how would I know if the word being read by fgets is in a new line?? 我怎么知道fgets读取的单词是否在新行中?

You're not supposed to call feof() before doing I/O, that's simply not how it works. 在执行I / O之前,您不应该调用feof() ,这根本不是它的工作原理。

If you're that interested in the location of each newline, read the file character by character instead, using fgetc() . 如果您对每个换行符的位置感兴趣,请使用fgetc()逐字符读取文件。 Then parse the character stream into words. 然后将字符流解析为单词。 This will make it trivial to notice when a newline comes along. 当换行符出现时,这很容易引起注意。

Do you really want to get three characters at a time (which is what you get for size 4, because fgets reads one less than size characters), thus getting the pieces 你真的想同时获得三个字符(这是你得到什么size 4,因为fgets读取小于一个size字符),从而得到片

C01 RD A A LB NAC ED C02 MC A E DF SLF AD C01 RD A A LB NAC ED C02 MC A E DF SLF AD

( denoting newline)? 表示换行符)? I don't think so, but rather you want four characters at a time and trim the word delimiters. 我不这么认为,但是您一次想要四个字符并修剪单词定界符。

char buffer[5];
char newline = 1;
while (fgets(buffer, sizeof buffer, fp))
{
    if (newline) puts("new line:");
    newline = buffer[3] == '\n';
    buffer[3] = '\0';
    puts(buffer);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM