compile and execute c program with argument
Solution 1
Your program isn't going to work very well - you're not providing enough arguments to read
and write
, for example (assuming you mean to be calling POSIX read(2)
and write(2)
, that is).
To answer your actual question, the problem appears to be that you're not providing any arguments. You need to run it something like:
./a.out FILE1 FILE2
replacing FILE1
with the name of your input file and FILE2
with the name of your output file.
Solution 2
Firstly read()
and write()
both take 3 arguments(only one given).
Secondly it should be used like this:
int ifilehandle = open(argc[1],O_RDONLY,S_IREAD);
int ofilehandle = open(argc[2],O_WRONLY,S_IWRITE);
char buffer[32767];
read(ifilehandle,&buffer,32766);
write(ofilehandle,&buffer,32766);
close(ifilehandle);
close(ofilehandle);
Thirdly, a.out should be invoked like this:
./a.out filename1.extension filename2.extension
lowcosthighperformance
Updated on June 04, 2022Comments
-
lowcosthighperformance almost 2 years
I am new in C program and linux, how can we compile and run this program?
I have tried
gcc example.c
then./a.out
but it gives an error likeinput file cannot be opened
( I have written this error in the read method)// example.c int main(int argc, char *argv[]) { char* input = argv[1]; read(input); char* output = argv[2]; write(output); return 0; }
Thanks.
-
omittones over 11 yearsIf you managed to run this, then the compilation was successful. Please add more info about read and write methods. Also, you need to pass two arguments on the command line:
./a.out FILE1 FILE2
. -
Basile Starynkevitch over 11 yearsYou really should compile with
gcc -std=gnu99 -Wall -g example.c -o myprog
, improve your code till you get no more warnings, then run./myprog
and learn to use thegdb
debugger
-
-
paulsm4 over 11 years+1 - you're absolutely correct. I just wasn't sure "read()" and "write()" were necessarily the best APIs for the OP. ADDITIONAL NOTE: if the OP uses "read()" or "write()", he should also
#include <unistd.h>
. See man read -
Basile Starynkevitch over 11 yearsI would use a power-of-two sized buffer (e.g. 16384), and read it in full.