SHARE
TWEET

Untitled

a guest Aug 23rd, 2019 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Writing to a file in C
  2.  
  3. 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.
  4.  
  5. # `writehello.c`
  6.  
  7. ```C
  8. /* Write "Hello world" to a text file specified as a command-line argument
  9.  
  10. * Compile and run using:
  11. gcc writehello.c -o writehello && writehello out.txt
  12. */
  13.  
  14. #include <stdio.h>
  15.  
  16. int main(int argc, char *argv[]) {
  17.     // Checl the number of arguments
  18.     if (argc != 2) {
  19.         fprintf(stderr, "Error: You need to give 1 argument\n");
  20.         return 1;
  21.     }
  22.     // Check the filename
  23.     FILE* fout = fopen(argv[1], "w");
  24.     if (fout == NULL) {
  25.         fprintf(stderr, "Error: couldn't open file\n");
  26.         return 2;
  27.     }
  28.     // Write to the file
  29.     fprintf(fout, "Hello world");
  30.    
  31.     // Close and exit
  32.     fclose(fout);
  33.     return 0;
  34. }
  35. ```
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top