Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  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. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement