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
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!!
You did
$ chmod +x simple_write.c
$ ./simple_write.c
when you should have done
$ cc simple_write.c -o simple_write$ chmod +x simple_write# On second thought, you probably don’t need this. $ ./simple_write
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 as gedit
).cc
is the historical name for the C compiler.
If you get cc: not found
(or something equivalent),
try the command again with gcc
(GNU C compiler).
If that doesn’t work,
When you get to writing more complicated programs, you are going to want to use
make simple_write
which has the advantages of
cc
or gcc
).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.
if (write(1, "Here is some data\n", 18) != 18)
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? Try
./simple_write >&-
You 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.