简体   繁体   English

fgetc()在函数中无法正常工作

[英]fgetc() doesn't work properly in function

I am trying to read a text file, character by character, with fgetc() function but it does not show any output. 我正在尝试使用fgetc()函数逐个字符地读取文本文件,但未显示任何输出。 It is a school project and it is still in very very simple way just to test the functionality of the program. 这是一个学校项目,并且仍然以非常非常简单的方式来测试程序的功能。

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

void fn1(FILE *f);
void fn9(FILE *fp, char, char);

int main() {
  FILE *fp = fopen("text.txt", "r");
  if (fp == NULL) {
    perror("Error: ");
    exit(1);
  }
  fn1(fp);
  fn9(fp, '0', '9');

  fclose(fp);
  return 0;
}

void fn1(FILE *f) {
  int num, sum = 0, count = 0;

  while (fscanf(f, "%d", &num) == 1) {
    if (num > 0) {
      sum += num;
      count++;
    }
  }
  printf("the avg of positive nums is %.2f", (float) sum / count);
}

void fn9(FILE *fp, char m, char n) {
  int ch;
  int count1 = 0, count2 = 0;

  while ((ch = fgetc(fp)) != EOF) {
    if (ch == m)
      count1++;
    if (ch == n)
      count2++;
    printf("%c", ch);
    if (ferror(fp))
      break;
  }

  printf("\n%c is seen %d times", m, count1);
  printf("\n%c is seen %d times", n, count2);

  fclose(fp);
}

The file's content that I test is: 我测试的文件内容为:

      90
      16
      -34
      100

After fn(fp) return, fp will point to the last location in the file. fn(fp)返回后,fp将指向文件中的最后一个位置。 It needs to be reset to the start of file before fn9 is called. 在调用fn9之前,需要将其重置为文件的开头。 Use fseek to point fp to the start of file and it should work :) 使用fseek将fp指向文件的开头,它应该可以工作:)

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

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