我看到人们最近在很多帖子中试图读取这样的文件.
码
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
char *path = argc > 1 ? argv[1] : "input.txt";
FILE *fp = fopen(path, "r");
if( fp == NULL ) {
perror(path);
return EXIT_FAILURE;
}
while( !feof(fp) ) { /* THIS IS WRONG */
/* Read and process data from file… */
}
if( fclose(fp) == 0 ) {
return EXIT_SUCCESS;
} else {
perror(path);
return EXIT_FAILURE;
}
}
Run Code Online (Sandbox Code Playgroud)
这个__CODE__循环有什么问题?
我用这个代码:
while ( scanf("%s", buf) == 1 ){
Run Code Online (Sandbox Code Playgroud)
什么是防止可能的缓冲区溢出的最佳方法,以便它可以传递随机长度的字符串?
我知道我可以通过调用例如限制输入字符串:
while ( scanf("%20s", buf) == 1 ){
Run Code Online (Sandbox Code Playgroud)
但我更愿意能够处理用户输入的任何内容.或者这不能使用scanf安全地完成,我应该使用fgets?