c - 使用 fget 时出现奇怪的情况

标签 c fgets

如果我打印整个字符串,一切看起来都很好,空格和缩进看起来很完美(我正在使用此代码加载源文件)。

但是,如果我尝试在缓冲区中打印单个字符,我会收到不应该有的字母。

例如,如果我打印 buffer[2] 我会在应该是空格的地方收到字母,但如果我打印整个字符串,则字母不在那里。

这是我的代码,不起作用:

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

int main(void) {

    char *buffer = (char*) malloc(100*sizeof(char));

    FILE *myFile;
    myFile = fopen("thisSourceFile.c", "r");

    if (!myFile) {

        printf("could not open file");
    }
    else {

        while(fgets(buffer,100,myFile)) {

        printf("%c \n",buffer[2]);

        }
    }

    fclose(myFile);
    free(buffer);
    buffer = NULL;

    return 0;
}

输出:

n
 n
 n

 t

 h


 I
 y

 f

 p

 l


 w

 p

 }



 r
 u


 e

正如你所见,它正在用空格打印字母。如果我打印整个字符串,这些字母就不存在。

最佳答案

如果您有兴趣解析源文件并处理每个字符,这可能是一个解决方案。

但是有两个常数; charsnum_lines_to_read。 M.M 在下面的评论中提到 isprint() 并不完全可移植,并且有一些需要注意的怪癖。

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

int main(void) {
    const int chars = 100; /* Num chars per line to read */
    const int num_lines_to_read = 3; /* Num lines to read */
    char *buffer = (char*) malloc(chars*sizeof(char));
    int i = 0, j = 0;

    FILE *myFile;
    myFile = fopen("thisSourceFile.c", "r");

    if (myFile == NULL) {
      printf("could not open file");
      fclose(myFile);
      return 1;
    }

    for(i=0; i<num_lines_to_read; i++)
    {
      if(fgets(buffer,chars,myFile) != NULL)
      {
        while(isprint((unsigned char) buffer[j]))
        {  
          printf("%c", (buffer[j]));
          j++;
        }
        j=0;
      }
    }

    fclose(myFile);
    free(buffer);

    return 0;
}

示例输出(本身!):

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

关于c - 使用 fget 时出现奇怪的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52047450/

相关文章:

c - 我的老师声称这个代码块在 O(n) 时间内运行……这是为什么呢?

C fgets 缓冲区大小

C - 使用 sscanf 读取多个整数和 float

c - fgets 在换行符后包含文本

循环中的 C 变量变化

c - Minix 3 stdio.h 无法识别文件 *f

c - 如何理解下面的代码?

c - 使用 fgets 从文件中读取行并将每一行与 c 中的 strncmp 进行比较

c - 跳过输入文件行的程序

c - Qsorting 二维指针数组