0
我使用XCode,我试图打开一个文件作为命令行参数传递,并输出作为该文件的命令行参数传递的行数,到C中的控制台。在XCode中,我的参数是“test.rtf”和“5”。我RTF样子:打开文件并输出在C
line 1 test
line 2 test
line 3 test
line 4 test
line 5 test
line 6 test
line 7 test
line 8 test
line 9 test
line 10 test
我曾试图与我在同一个文件夹我的XCode项目文件夹RTF,并在该可执行文件是Debug文件夹。我的代码是:
#include <stdio.h>
#include <stdlib.h>
#define CORRECT_PARAMETERS 2
int main(int argc, char *argv[])
{
int x;
if (argc != CORRECT_PARAMETERS) {
printf("Wrong number of parameters inputted.");
}
else {
FILE *inFp; /*declare a file pointer */
if ((inFp = fopen(argv[0], "r") == NULL)) {
fprintf(stderr, "Can't open file");
exit(EXIT_FAILURE);
}
else {
for (x = 1; x <= argv[1]; x++) {
while ((x = fgetc(inFp)) != EOF) {
printf("%c", x);
}
}
}
fclose(inFp);
}
}
我知道我的代码可能不正确在命令行输出线输入的数字,但我不能让刚刚打开该文件的开头部分的工作。输出的是:
Wrong number of parameters inputted.
谢谢!
更不用说for循环测试'x',但while循环始终保证'x = EOF'在循环的条件部分被测试之前。因此,根据'EOF'的定义,for循环将运行一次并终止,否则它将无限循环。 – 2009-11-16 00:21:14
好的答案,@汤姆。 +1 - 但我固定极限分配使用argv [2]而不是argv [1](你已经提到过但没有捕获到这个实例)。 – paxdiablo 2009-11-16 01:02:10