用C打开文件并输出

用C打开文件并输出,c,C,我正在使用XCode,我试图打开一个作为命令行参数传递的文件,并将作为该文件的命令行参数传递的行数输出到C中的控制台。在XCode中,我的参数是“test.rtf”和“5”。我的rtf看起来像: 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项目文件夹相同的文件夹中,以及可执行文件

我正在使用XCode,我试图打开一个作为命令行参数传递的文件,并将作为该文件的命令行参数传递的行数输出到C中的控制台。在XCode中,我的参数是“test.rtf”和“5”。我的rtf看起来像:

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。我的代码是:

#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);
 }

}
谢谢

在XCode中,我的参数是“test.rtf”, 及"5

那么argc将取3的值

 if ((inFp = fopen(argv[0], "r") == NULL)) 
argv[0]:程序的名称

argv[1]:“test.rtf”

argv[2]:5

您应该更新定义的常量,使其值为3

 if ((inFp = fopen(argv[0], "r") == NULL)) 
argv[0]是正在执行的程序的名称

您要查找的(第一个参数)是argv[1]

int x;
for (x = 1; x <= argv[1]; x++) {

赋值x=1只发生一次!!!。将inFp读入另一个变量。

更不用说for循环测试
x
,但是内部的while循环总是在测试循环的条件部分之前确保
x=EOF
。因此,根据EOF的定义,for循环要么运行一次并终止,要么无限循环。回答得好,@Tom+1-但我修复了使用argv[2]而不是argv[1]的限制分配(您已经提到了这一点,但尚未捕捉到该实例)。
int x;
int limit = atoi(argv[2]);
for (x = 1; x <= limit; x++) 
 while ((x = fgetc(inFp)) != EOF)