ray smith
ray smith

Reputation: 380

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. 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

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

Any suggestions?

Upvotes: 0

Views: 1804

Answers (2)

Jasen
Jasen

Reputation: 12412

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. and file operations like fopen fgets etc will not work on it.

Upvotes: 3

twinlakes
twinlakes

Reputation: 10228

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.

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

Upvotes: 3

Related Questions