2

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

2
  • 1
    If 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. Commented Oct 13, 2012 at 18:22
  • You 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 the gdb debugger Commented Oct 14, 2012 at 7:07

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

+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
I would use a power-of-two sized buffer (e.g. 16384), and read it in full.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.