Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • File handling operation in c language

    • 0
    • 1
    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 409
    Comment on it

    File handling in C

    In C programming language we use a structure pointer of file type for declaring a file.
    Syntax:-

    FILE *fp;
    

    The fopen() function is used to create a new file or to open existing file.

    Syntax :

    *fp = FILE *fopen (const char *filename, const char *mode);
    

    The fclose() function is used to close an already opened file.

    Syntax :

    int fclose( FILE *fp );
    

    Source code using Input/Output operation on file

    #include
    #include
    main()
    {
     FILE *fp;
     char ch;
     fp = fopen("one.txt", "w");
     printf("Enter data");
     while( (ch = getchar()) != EOF) {
        putc(ch,fp);
     }
     fclose(fp);
     fp = fopen("one.txt", "r");
     while( (ch = getc()) != EOF)
        printf("%c",ch);
     fclose(fp);
    }
    

    Here fclose() function closes the file and returns zero on success or EOF if there is an error in closing the file.This EOF is a constant defined in the header file stdio.h.

    Reading and Writing from File using fprintf() and fscanf()

    #include
    #include
    main()
    {
     FILE *fp;
     char ch;
     fp = fopen("one.txt", "w");
     printf("Enter data");
     while( (ch = getchar()) != EOF) {
        putc(ch,fp);
     }
     fclose(fp);
     fp = fopen("one.txt", "r");
     while( (ch = getc()) != EOF)
        printf("%c",ch);
     fclose(fp);
    }
    

    In this program, we have created two FILE pointers and both are referring to the same file but in different modes. fprintf() function directly writes into the file, while fscanf() reads from the file, which can then be printed on console using standard printf() function

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: