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 项目文件夹相同的文件夹中以及可执行文件所在的 Debug 文件夹中使用我的 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);
 }

}

我知道我的代码可能不正确地输出在命令行输入的行数,但我无法让开始部分只打开文件。输出的是:

Wrong number of parameters inputted.  

谢谢!

最佳答案

In XCode, my arguments are "test.rtf", and "5".

那么argc就取3的值

argv[0] : name of the program

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++) {

这闻起来像麻烦。您正在将 C 字符串与整数进行比较。 试试这个(包括使用参数 2 而不是 1,如上所述):

int x;
int limit = atoi(argv[2]);
for (x = 1; x <= limit; x++) 

在这里您要更改 X 的值。

 while ((x = fgetc(inFp)) != EOF)

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

关于c - 在 C 中打开文件并输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1739392/

相关文章:

c - 函数在另一个函数中带有指针参数?

c - 如何在 Visual Studio Express 上运行 AuBio(一个开源 C 程序)

c - Gcc:尝试执行 'cc1' 时出错:execvp:没有这样的文件或目录

c - 数组 : accessing array elements by inverting the index variable with the array itself yields the same result

c - 将指针插入 GCC 中的 eax 和 ebx 寄存器

c - const char[] 变量之间的区别;和 "some chars"

实现 TCP 服务器时连接被拒绝

c - extern 关键字是什么意思?

c++ - 测试结果乘加减除可能为一组数字

c - 决定尝试一下 C 中的自制函数