As a beginner, I am trying to write a simple c program to learn and execute the "write" function.
I am trying to execute a simple c program simple_write.c
#include <unistd.h>
#include <stdlib.h>
int main()
{
if ((write(1, “Here is some data\n”, 18)) != 18)
write(2, “A write error has occurred on file descriptor 1\n”,46);
exit(0);
}
I also execute chmod +x simple_write.c
But when i execute ./simple_write.c, it gives me syntax error near unexpected token '('
Couldn't figure out why this happens ??
P.S: The expected output is:-
$ ./simple_write
Here is some data
$
You did
when you should have done
In words: compile the program to create an executable
simple_write
(without.c
) file, and then run that. What you did was attempt to execute your C source code file as a shell script.Notes:
simple_write
file will be a binary file. Do not look at it with tools meant for text files (e.g.,cat
,less
, or text editors such asgedit
).cc
is the historical name for the C compiler. If you getcc: not found
(or something equivalent), try the command again withgcc
(GNU C compiler). If that doesn’t work,When you get to writing more complicated programs, you are going to want to use
which has the advantages of
cc
orgcc
).And, in fact, you should be able to use the above command now. This may (or may not) simplify your life.
P.S. Now that this question is on Stack Overflow, I’m allowed to talk about the programming aspect of it. It looks to me like it should compile, but
The first
write
line has more parentheses than it needs.should work.
write
line, I count the string as being 48 characters long, not 46.By the way, do you know how to make the first
write
fail, so the second one will execute? TryYou cannot execute C source code in Linux (or other systems) directly.
C is a language that requires compilation to binary format.
You need to install C compiler (the actual procedure differs depending on your system), compile your program and only then you can execute it.
Currently it was interpreted by shell. The first two lines starting with
#
were ignored as comments. The third line caused a syntax error.Ok,
I got what i was doing wrong.
These are the steps that I took to get my problem corrected:-
$ gedit simple_write.c
Write the code into this file and save it (with .c extension).
$ make simple_write
$ ./simple_write
And I got the desired output.
Thanks!!