如何确定在读取所有字母之前fgets是否停止? [英] How to determine if fgets stopped before all letters were read?

查看:104
本文介绍了如何确定在读取所有字母之前fgets是否停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做这样的事情:

char buf[100];              
int n = 0;                  
char save[100][100];        

while (fgets(buf,100, file)!=NULL) {
    strcpy(save[n], buf);
    printf("%s",buf);
    n++;
}

我以前用错误处理打开了FILE = *file. 我只想读取少于或等于100个字符的行.那些具有更多字符的字符,我想忽略并将一些特殊消息写入保存"数组或perrorstout流.

I opened a FILE = *file with error handling before. I only want to read the lines that have less than or equal to 100 characters. Those that feature more characters, I want to ignore and write some special message to the "save" array or to the perror or stout stream.

但是,我怎么可能知道我刚好是100个字符还是我的fgets只是停止阅读而已?

However, how can I possibly know whether I got exactly 100 characters or my fgets has simply stopped reading at its limit?

我怎么知道我是否一开始就获得了100多张?

How can I know whether I got more than 100 in the first place?

推荐答案

首先让我们假设fgets()不会读取空字符.如果是这样,则以下方法可能不够用.

First let us assume that fgets() is not going to read a null character. If it does, the following method may be insufficient.

我只想读取少于或等于100个字符的行.那些功能更多的字符,我想忽略,并向保存"数组中写入一些特殊消息

I only want to read the lines that have less than or equal to 100 characters. Those that feature more characters, I want to ignore and write some special message to the "save" array

问题1. '\n' Enter 100个字符的一部分吗?让我们假设事实并非如此.

Problem 1. Is the '\n' or Enter part of the 100 characters? Let us assume it is not.

OP似乎仍然想读取该行,无论该行长于或短于100个字符或COLS个字符,那么这只是一个如何处理它的问题.

OP appears to still want to read the line, be it longer or shorter than 100 or COLS characters, it is just a question of what to do with it then.

推荐COLS+3的缓冲区.一个用于空字符,一个用于'\n',一个用于超长行检测.

Recommend a buffer of COLS+3. One for the null character, one for the '\n' and one for extra long line detection.

#define ROWS 100
#define COLS 100
char save[ROWS][COLS+1];  // +1 for \0      
char buf[COLS + 3];              
int n = 0;                  

while (n < ROWS && fgets(buf, sizeof buf, file)!=NULL) {
  size_t len = strlen(buf);
  bool EOLorEOFfound = false;

  // lop off potential \n
  if (len > 0 && buf[len - 1] == '\n') {
    buf[--len] = '\0';
    EOLorEOFfound = true;
  }

  // if line is too long ...
  if (len > COLS) {
    // consume rest of line
    while (!EOLorEOFfound) {
      int ch = fgetc(file);
      EOLorEOFfound = ch == '\n' || ch == EOF;
    }
    // write some special message to the "save" array
    assert(COLS >= 3);
    strcpy(save[n], "***");
  } 
  // Line not too long
  else {
    strcpy(save[n], buf);  // or memcpy(save[n], buf, len+1);
    printf("%s\n", buf);
  }
  n++;
}

这篇关于如何确定在读取所有字母之前fgets是否停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆