从命令行传递文件名以读取文件内容

问题描述 投票:-2回答:1

我有一个函数./transform,需要为输入和输出文件接受两个命令行参数。

像这样:./transform "inputfile" "outputfile"

然后我尝试使用fopen读取文件,将文件中的每个字符存储到字符数组char token[1024]中。输入文件中的字符总数始终<= 1024。

我收到的关于fopen没有适量参数的错误。这是我想要完成的伪代码。

void main(FILE *inputFile, FILE *outputFile){
    char token[1024];
    token = fopen(&inputFile, "r");
}

是的,我知道我正在尝试将一个FILE值赋给Char值...我这样写它是为了表明我希望inputFile中的每个字符都存储在字符数组中。我不确定如何正确地做到这一点。执行程序代码(将hex和int值从文件转换为ASCII)后,我需要将转换后的ASCII文本保存到用户定义的输出文件中。

c command-line-arguments fopen argv argc
1个回答
0
投票

您尝试的代码几乎没有问题,首先在这里

void main(FILE *inputFile, FILE *outputFile){ }

你试图改变main()的原型,这是不正确的。根据C Standard第5.1.2.2.1节程序启动,它应该是

int main(void) { /* ... */ }

要么

int main(int argc, char *argv[]) { /* ... */ }

所以就这样吧

int main(int argc, char *argv[]) {
    /*some_code */
}

接下来,从命令行使用fopen()打开文件,这个

token = fopen(&inputFile, "r");

是完全错误的,因为fopen()返回FILE*的论据而不是char*和你提供给fopen()的论点也是错误的。请阅读fopen()的手册页

FILE *fopen(const char *path, const char *mode);

示例代码

int main(int argc, char *argv[]) {
  if( argc!= 3 ) { /*if user input is not correct, inform user */
     printf("./transform inputfile outputfile \n");
     return 0;
  }
  FILE *fp = fopen(argv[1],"r); 
  if(fp == NULL) {
     /* error handling */
     return 0;
  }
  /* do_stuff_with_fp */  
}
© www.soinside.com 2019 - 2024. All rights reserved.