如果我打印整个字符串,一切看起来都很好,空格和缩进看起来很完美(我正在使用此代码加载源文件)。
但是,如果我尝试在缓冲区中打印单个字符,我会收到不应该有的字母。
例如,如果我打印 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
正如你所见,它正在用空格打印字母。如果我打印整个字符串,这些字母就不存在。
最佳答案
如果您有兴趣解析源文件并处理每个字符,这可能是一个解决方案。
但是有两个常数; chars
和num_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/