简体   繁体   English

如何将纯文本文件作为命令行参数传递

[英]How to pass a plain text file as a command line argument

I'm trying to pass a file to my c++ program via the command line. 我试图通过命令行将文件传递给我的c ++程序。 What I am trying is this: 我正在尝试的是这样的:

g++ main.cpp quadTree.h Rectangle.h quadTree.cpp Rectangle.cpp obstacles_copy.txt -lX11 -lm -L/usr/X11R6/lib

I keep getting this error: 我不断收到此错误:

/usr/bin/ld:obstacles_copy.txt: file format not recognized;
treating as linker script
/usr/bin/ld:obstacles_copy.txt:1: syntax error
collect2: error: ld returned 1 exit status**

I open the file in my main() using 我使用以下命令在main()中打开文件

FILE *fp=fopen(argv[1],"r");

Any suggestions? 有什么建议么?

When you say "pass a file", what exactly do you mean? 当您说“传递文件”时,您的意思是什么?

In your example, you are trying to compile the text file into your binary, which is giving you problems. 在您的示例中,您试图将文本文件编译为二进制文件,这给您带来了问题。

You should instead pass in the file name at runtime as a command line argument or feed in the file to your stdin using cmd < file . 相反,您应该在运行时将文件名作为命令行参数传递,或使用cmd < file将文件输入标准输入。

To pass in a file at runtime, you would call your program in bash with ./myprogram filename , then in your main , you can access the filename as argv[1] , making sure to handle the case where argc == 1 要在运行时传递文件,您可以使用./myprogram filename在bash中调用程序,然后在mainargv[1]访问文件名,确保处理argc == 1

Compile first 先编译

g++ main.cpp quadTree.h Rectangle.h quadTree.cpp Rectangle.cpp -lX11 -lm -L/usr/X11R6/lib

Then execute 然后执行

./a.out obstacles_copy.txt 

if you want to build the text file into the binary that can be done by using objcopy to convert it to a format that gcc will understand, but thus converted it will be a memory object (a big array of char) not a file. 如果要将文本文件构建为二进制文件,可以通过使用objcopy将文本文件转换为gcc可以理解的格式来完成,但是转换后的文本文件将是内存对象(大字符数组)而不是文件。 and file operations like fopen fgets etc will not work on it. 和文件操作,例如fopen fgets等将无法在其上运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM