Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Writing to a file in C
- The file `writehello.c` below represents a simple program in C for writing "Hello world" to a file, whose filename is specified as a command-line argument. The program includes error checking for the number of arguments, and the validity of the filename.
- # `writehello.c`
- ```C
- /* Write "Hello world" to a text file specified as a command-line argument
- * Compile and run using:
- gcc writehello.c -o writehello && writehello out.txt
- */
- #include <stdio.h>
- int main(int argc, char *argv[]) {
- // Checl the number of arguments
- if (argc != 2) {
- fprintf(stderr, "Error: You need to give 1 argument\n");
- return 1;
- }
- // Check the filename
- FILE* fout = fopen(argv[1], "w");
- if (fout == NULL) {
- fprintf(stderr, "Error: couldn't open file\n");
- return 2;
- }
- // Write to the file
- fprintf(fout, "Hello world");
- // Close and exit
- fclose(fout);
- return 0;
- }
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement