This blog is under construction

Sunday 28 July 2013

C program to create a file and store "hello world" in it.

Write a C program to create a file and store "hello world" in it.


  #include <stdio.h>
  #include <string.h>
  #define MAX 256

  int main(int argc, char **argv) {
        FILE *fp;
        char str[MAX];

        /* open the input file in write mode */
        fp = fopen(argv[1], "w");

        /* In case if file pointer is NULL */
        if (!fp) {
                printf("Unable to open the given file!!\n");
                return 0;
        }

        /* get the input string from the user */
        printf("Enter hello world:");
        fgets(str, MAX, stdin);

        /* print the input string to the input file */
        fprintf(fp, "%s\n", str);

        /* close the opened file */
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out data.txt 
  Enter hello world:hello world
  jp@jp-VirtualBox:~/$ cat data.txt 
  hello world






SEE ALSO

    No comments:

    Post a Comment