我试图找出为什么这不是打印,我试图从通过命令提示符输入的文本文件中打印每个字母,但我只是得到一个空输出...我做错了什么,为什么这不起作用?我觉得这在逻辑上应该有效。感谢。
int main(int argc, char *argv[]) {
FILE *fp;
int i;
for (i = 1; i < argc; i++) {
printf("%s\n", argv[i]);
fp = fopen(argv[i], "r");
while (!feof(fp)) {
puts(fp);
}
fclose(fp);
}
return 0;
}
答案 0 :(得分:1)
您正在尝试打印文件指针:
puts(fp);
阅读puts()
的手册 - 不是它需要的。
要读取char-by-char并在stdout上打印,您可以执行以下操作:
int ch;
fp = fopen(argv[i], "r");
if (!fp) {
perror("fopen");
exit(1);
}
while((ch=fgetc(fp)) != EOF) {
putchar(ch);
}
flcose(fp);
除非你传递多个文件名作为参数,否则你的外部循环没有多大意义。
答案 1 :(得分:1)
您的计划有多个问题:
您不测试fopen()
的返回值:如果任何命令行参数无法作为读取流打开,程序将调用未定义的行为。
while(!feof(fp))
不正确。请阅读:Why is “while ( !feof (file) )” always wrong?
puts(fp);
不正确,因为fp
是FILE *
,而不是字符串。使用循环一次一个字节地复制文件内容。
以下是更正后的版本:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
FILE *fp;
int i, c;
for (i = 1; i < argc; i++) {
fp = fopen(argv[i], "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", argv[i], strerror(errno));
} else {
printf("%s\n", argv[i]);
while ((c = getc(fp)) != EOF) {
putchar(c);
}
fclose(fp);
}
}
return 0;
}
答案 2 :(得分:0)
int main(int argc, char *argv[]) {
FILE *fp;
int i;
char buff[128];
for (i = 1; i < argc; i++) {
printf("\n%s\n", argv[i]);
if(NULL == (fp = fopen(argv[i], "r"))){//check open file
perror("fopen");
continue;
}
while (fgets(buff, sizeof buff, fp)) {//read into buffer
fputs(buff, stdout);//print buffer (not add newline)
}
fclose(fp);
}
return 0;
}