File read write in plain C

Discussion in 'C' started by Sanskruti, Feb 13, 2007.

  1. Sanskruti

    Sanskruti New Member

    Joined:
    Jan 7, 2007
    Messages:
    108
    Likes Received:
    18
    Trophy Points:
    0
    Occupation:
    Software Consultant
    Location:
    Mumbai, India
    Refer to the recent articles on Understanding File Handling Functions in C & Understanding Advance File Handling Functions in C

    Opening A File



    Before we can write information to a file on a disk or read it, we must open the file. Opening a file establishes a link between the program and the operating system, about, which file we are going to access and how. We provide the operating system with the name of the file and whether we plan to read or write to it. The link between our program and the operating system is a structure called FILE which has been defined in the header file “stdio.h” . Therefore, it is necessary to always include this file when we are doing high level disk I/O. When we request the operating system to a file, what we get back is a pointer to the structure FILE. That is why, we make the following declaration before opening the file,

    FILE*fp ;

    Each file we open will have its own FILE structure. The FILE structure contains information about the file being used, such as its current size, its location in memory etc. More importantly it contains a character pointer which points to the character that is about to get read.

    Now let us understand the following statements,

    FILE *fp ;
    fp = fopen ( “PR1.C”, “r” ) ;

    fp is a pointer variable, which contains address of the structure FILE which has been in the header file “stdio.h”.

    fopen( ) will open a file “PR1.C” in ‘read’ mode, which tells the compiler that we would be reading the contents of the file. Note that “r” is a string and not a character; hence the double quotes and not single quotes.

    In fact, fopen( ) performs three important tasks when you open the file in “r” mode:

    (a) Firstly it searches on the disk the file to be opened.
    (b) If the file is present, it loads the file from the disk into memory. Of course if the file is very big, then it loads the file part by part.If the file is absent, fopen( ) returns a NULL.NULL is a macro defined in “stdio.h” which indicates that you failed to open the file.
    (c) It sets up a character pointer which points to the first character of the chunk of memory where the file has been loaded.

    Reading from A file



    Once the file has been opened for reading using fopen( ), the file’s contents are brought into memory and a pointer points to the very first character. To read the file’s contents from memory there exists a function called fgetc( ). This has been used in our sample program through,

    ch = fgetc ( fp ) ;

    fgetc( ) reads the character from current pointer position, advances the pointer position so that it now points to the next character, and returns the character that is read, which we collected in the variable ch. Note that once the file has been opened, we refer to the file through the file pointer fp.

    We have to use the function fgetc( ) within an indefinite while loop. There has to be a way to break out of this while,it is the moment we reach the end of file. End of file is signified by a special character in the file, when it is created. This character can also be generated from the keyboard by typing ctrl Z.

    While reading from the file, when fgetc( ) encounters this special character, instead of returning the character that it has read, it returns the macro EOF. The EOF macro has been defined I the file “stdio.h”. In place of the function fgetc( ) we could have as well used the macro getc( ) with the same effect.

    Opening A File



    There is a possibility that when we try to open a file using the function fopen( ), the file may not be opened. While opening the file in “r” mode, this may happen because the file being opened may not be present on the disk at all. And you obviously cannot read a file which doesn’t exist. Similarly, while opening the file for writing, fopen( ) may fail due to a number of reasons, like, disk space may be insufficient to open a new file, or the disk may be write protected and so on.

    So it is important for any program that accesses disk files to check whether a file has been opened successfully before trying to read or write to the file. If the file opening fails due to any of the several reasons mentioned above, the fopen( ) function returns a value NULL (defined in “stdio.h” as #define NULL 0).

    Here is how this can be handled in a program…

    Code:
    #include “stdio.h”
    main()
    {
             FILE*fp ;
    
             Fp = fopen ( “PR1.C”,”r” ) ;
             if( fp == NULL )
             {
                   puts ( “cannot open file” ) ;
                   exit() ;
             }
    }

    File Opening Modes



    We open the file in read ( “r” ) mode. However, “r” is but one of the several modes in which we can open a file. Following is a list of all possible modes in which a file can be opened . the tasks performed by fopen( ) when a file is opened in each of these modes are also mentioned.

    r :- Searches file. If the file exists, loads it into memory and sets up a pointer which points to the first character in it. If the file doesn’t exit it returns NULL.

    Operations possible – reading from the file.

    w :- Searches file. If the file exists, its contents are overwritten. If the file doesn’t exit, a new file is created. Returns NULL, if unable to open file.

    Operations possible – writing to the file.

    a :- Searches file. If the file exists, loads it into memory and sets up a pointer which points to the first character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.

    Operations possible – appending new contents at the end of file.

    r+ :- Searches file. If it exists, loads it into memory and sets up a pointer which points to the first character in it. If file doesn’t exist it returns NULL.

    Operations possible – reading existing contents, writing new contents, modifying existing contents of the file.

    w+ :- Searches file. If the file exists, its contents are destroyed. If the file doesn’t exist a new file is created. Returns NULL, if unable to open file.

    Operations possible – writing new contents, reading them back and modifying existing contents of the file.

    a+ :-Searches file. If the file exists, loads it in to memory and sets up a pointer which points to the first character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.

    Operations possible – reading existing contents, appending new contents to end of file. Cannot modify existing contents.

    Writing to A File



    The fputc( ) function is similar to the putch( ) function, in the sense that both output characters. However, putch( ) function always writes to the VDU, whereas, fputc( ) writes to the file. Which file? The file signified by ft. the writing process continues till all characters from the source file have been written to the target file, following which the while loop terminates.

    We have already seenthe function fgetc( ) which reads characters from a file. Its

    Counterpart is a function called fputc( ) which writes characters to a file. As a practical use of these character I/O functions we can copy the contents of one file into another, as demonstrated in the following example. This program takes the contents of a text file and copies them into another text file, character by character.

    Example

    Code:
    #include “stdio.h”
    main()
    {
            FILE *fs, *ft ;
            char ch ;
    
            fs = fopen ( “pr1.c”, “r” ) ;
            if ( fs == NULL )
            {
                   puts ( “Cannot open source file” ) ;
                   exit( ) ;
            }
    
            ft = fopen ( “pr2.c”, “w” ) ;
            if ( ft == NULL )
            {
                   puts ( “Cannot open target file” ) ;
                   fclose ( fs ) ;
                   exit( ) ;
            }
    
            while ( 1 )
            {
                   ch = fgetc ( fs ) ;
    
                   if ( ch == EOF )
                          break ;
                   else
                        
                           fputc ( ch, ft )  ;
            }
    
            fclose ( fs ) ;
            fclose (t
    }

    Closing The File



    When we have finished reading from the file, we need to close it. This is done using the function fclose( ) through the statement,

    fclose ( fp ) ;

    this deactivates the file and hence it can no longer be accessed using getc( ). Once again we don’t use the filename but the file pointer fp.

    Refer to the recent articles on Understanding File Handling Functions in C & Understanding Advance File Handling Functions in C
     
  2. Peter_APIIT

    Peter_APIIT New Member

    Joined:
    Apr 11, 2007
    Messages:
    92
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Malaysia
    I don't understand what this statemnet does fputc ( ch, ft ) .

    Your explanation and teaching is greatly appreciated by me and others.

    Thanks for your help.
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    fputc ( ch, ft ) puts the character ch into the file ft opened by fopen
     
  4. Peter_APIIT

    Peter_APIIT New Member

    Joined:
    Apr 11, 2007
    Messages:
    92
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Malaysia
    Is it possible to copy directly from a file to another file in c without go through the ch ?

    Thanks for your help.


    Hope this can help others also.
     
  5. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Nope or probably I have no idea relating to the same and you can always try that.
     
  6. Peter_APIIT

    Peter_APIIT New Member

    Joined:
    Apr 11, 2007
    Messages:
    92
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Malaysia
    OK. Thanks for your patient and explanations.
     
  7. daniel_bingamon

    daniel_bingamon New Member

    Joined:
    Mar 14, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Programming
    Location:
    Kings Mills, OH
    You could read the file in blocks using the "fread" and "fwrite" functions which would operate faster.

    One way to "copy" files is to use the "system" which runs command line operates. You could also write a file to the hard disk that performs a script, like a VB script and then execute it using the "WinExec" function.
     
  8. davidk

    davidk New Member

    Joined:
    Mar 25, 2010
    Messages:
    16
    Likes Received:
    1
    Trophy Points:
    0
    Home Page:
    http://www.firmdev.com/firm_framework
    There is no info about 'b' character in 2nd parameter of fopen() function. It's worh saying about it because it is very useful when dealing with binary data instead of just text.
    Code:
    FILE *f = fopen("some_file", "rb"); //we open binary file for reading
    
    without knowing of some_file is binary the C standard library will think it is text and strip away end-of-line characters, that would break the further parsing of that binary file.
     
  9. Poonamol

    Poonamol New Member

    Joined:
    Mar 31, 2010
    Messages:
    33
    Likes Received:
    0
    Trophy Points:
    0
    I want to read a file and from some location i need to copy the contents and write into another file.
    E.g.
    Oldfile.txt contents,
    ABC987;26/09/2006ABC988;27/09/2006ABC989;28/09/2006ABC990;29/09/2006ABC991;30/09/2006ABC992;25/09/2006ABC993;24/09/2006ABC994;23/09/2006

    Now while reading a file i need to get some location of line say ABC990;..... and from this line i want to copy contents into another file say Newfile.txt.

    Anyone help me out ASAP. I am a new to file handling in C.
     
  10. missnirupma

    missnirupma New Member

    Joined:
    Jul 23, 2010
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Write a program in C that will help an elementary
    school student learn multiplication. Use rand function to produce two positive one-digit integers. It
    should then type a question such as: How much is 6 times 7?
    The student then types the answer. Your program checks the student’s answer. If it is correct, print
    “Very Good!” and then ask another multiplication question. If the answer is wrong, print, “No, Please
    try again.” And then let the student try the same question again repeatedly until the student finally gets
    it right.
     
  11. nalwoga

    nalwoga New Member

    Joined:
    Feb 22, 2011
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hello may you please give me a sample of a program about reading and writing to files?
     
  12. nalwoga

    nalwoga New Member

    Joined:
    Feb 22, 2011
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    May you send me a sample program about reading and writing to files
     
  13. duaa

    duaa New Member

    Joined:
    Mar 12, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    thank you
    i try to use your lesson but i have errors in file
    can you help me???
    Code:
    /* global.h */
    
    #include <stdio.h> /* include declarations for i/o routines */
    #include <ctype.h> /* ... and for character test routines */
    #include <stdlib.h> /* ... and for some standard routines, such as exit */
    #include <string.h> /* ... and for string routines */
    
    #define BSIZE 128 /* buffer size */
    #define NONE -1
    #define EOS '\0'
    
    #define NUM 256
    #define DIV 257
    #define MOD 258
    #define ID 259
    #define DONE 260
    #define PLUS 243
    #define MINUS 255
    int tokenval = NONE; /* value of token attribute */ 
    int lineno = 1;
    
    struct entry { /* form of symbol table entry */
    char *lexptr; 
    int token; 
    };
    
    struct entry symtable[]; /* symbol table */
    
    void init(); /* loads keywords into symtable */
    void error(char* m); /* generates all error messages */
    int lexan(); /* lexical analyzer */
    void parse(); /* parses and translates expression list */
    int insert(char *s, int tok); /* returns position of entry for s */
    int lookup(char *s); /* returns position of entry for s */
    void emit (int t, int tval); /* generates output */
    /* init.c */
    
    struct entry keywords[] = {
    { "div", DIV },
    { "mod", MOD, },
    { "plus", PLUS },
    { "minus", MINUS},
    { 0, 0 }
    };
    
    void init() /* loads keywords into symtable */
    {
    struct entry *p;
    for (p = keywords; p->token; p++)
    insert(p->lexptr, p->token);
    }
    /* symbol.c */
    
    
    #define STRMAX 999 /* size of lexemes array */
    #define SYMMAX 100 /* size of symbol table */
    
    char lexemes[STRMAX];
    int lastchar = - 1; /* last used position in lexemes */
    struct entry symtable[SYMMAX];
    int lastentry = 0; /* last used position in symtable */
    
    int lookup(char *s) /* returns position of entry for s */
    {
    int p;
    for (p = lastentry; p > 0; p = p - 1)
    if (strcmp(symtable[p].lexptr, s) == 0)
    return p;
    return 0;
    }
    
    int insert(char *s, int tok) /* returns position of entry for s */
    {
    int len;
    len = strlen(s); /* strlen computes length of s */
    if (lastentry + 1 >= SYMMAX)
    error ("symbol table full");
    if (lastchar + len + 1 >= STRMAX)
    error ("lexemes array full");
    lastentry = lastentry + 1;
    symtable[lastentry].token = tok;
    symtable[lastentry].lexptr = &lexemes[lastchar + 1];
    lastchar = lastchar + len + 1;
    strcpy(symtable[lastentry].lexptr, s);
    return lastentry;
    }
    /* lexer.c */
    
    
    char lexbuf[BSIZE];
    
    
    int lexan () /* lexical analyzer */
    {
    
    int t;
    while(1) {
    t = fgetc (fs);
    if (t == ' ' || t == '\t')
    ; /* strip out white space */
    else if (t == '\n')
    lineno = lineno + 1;
    else if (isdigit (t)) { /* t is a digit */
    ungetc(t, fs);
    fscanf(fs,"%d", &tokenval);
    return NUM;
    }
    else if (isalpha(t)) { /* t is a letter */
    int p, b = 0;
    while (isalnum(t)) { /* t is alphanumeric */
    lexbuf [b] = t; 
    t = fgetchar (fs);
    b = b + 1;
    if (b >= BSIZE)
    error("compiler error");
    }
    lexbuf[b] = EOS;
    if (t != EOF)
    ungetc(t, fs);
    p = lookup (lexbuf);
    if (p == 0)
    p = insert (lexbuf, ID);
    tokenval = p;
    return symtable[p].token;
    }
    else if (t == EOF)
    return DONE;
    else {
    tokenval = NONE;
    return t;
    }
    }
    }
    
    /* emitter.c */
    void emit (int t, int tval) /* generates output */
    {
    switch(t) {
    case '+' : case '-' : case '*' : case '/':
    fprintf(ft,"%c\n", t); break;
    case PLUS :
    fprintf(ft,"PLUS\n"); break;
    case MINUS :
    fprintf(ft,"MINUS\n"); break;
    case DIV:
    fprintf(ft,"DIV\n"); break; 
    case MOD:
    fprintf(ft,"MOD\n"); break;
    case NUM:
    fprintf(ft,"%d\n", tval); break;
    case ID:
    fprintf(ft,"%s\n", symtable[tval].lexptr); break; 
    default: 
    fprintf(ft,"token %d, tokenval %d\n", t, tval);
    }
    }
    /* parser.c -- without the optimizations */
    
    int lookahead;
    
    void match(int);
    void start(), list(), expr(), moreterms(), term(), morefactors(), factor();
    
    void parse() /* parses and translates expression list */
    {
    lookahead = lexan();
    start();
    }
    
    void start ()
    {
    /* Just one production for start, so we don't need to check lookahead */
    list(); match(DONE);
    }
    
    void list()
    {
    if (lookahead == '(' || lookahead == ID || lookahead == NUM) {
    expr(); match(';'); list();
    }
    else {
    /* Empty */
    }
    }
    
    void expr ()
    {
    /* Just one production for expr, so we don't need to check lookahead */
    term(); moreterms();
    }
    
    void moreterms()
    {
    if (lookahead == '+') {
    match('+'); term(); emit('+', tokenval); moreterms();
    }
    else if (lookahead == '-') {
    match('-'); term(); emit('-', tokenval); moreterms();
    }
    else {
    /* Empty */
    }
    }
    
    void term ()
    {
    /* Just one production for term, so we don't need to check lookahead */
    factor(); morefactors();
    }
    
    void morefactors ()
    {
    if (lookahead == '*') {
    match('*'); factor(); emit('*', tokenval); morefactors();
    }
    else if (lookahead == '/') {
    match('/'); factor(); emit('/', tokenval); morefactors();
    }
    else if (lookahead == PLUS) {
    match(PLUS); factor(); emit(PLUS, tokenval); morefactors();
    }
    else if (lookahead == MINUS) {
    match(MINUS); factor(); emit(MINUS, tokenval); morefactors();
    }
    else if (lookahead == DIV) {
    match(DIV); factor(); emit(DIV, tokenval); morefactors();
    }
    else if (lookahead == MOD) {
    match(MOD); factor(); emit(MOD, tokenval); morefactors();
    }
    else {
    /* Empty */
    }
    }
    
    void factor ()
    {
    if (lookahead == '(') {
    match('('); expr(); match(')');
    }
    else if (lookahead == ID) {
    int id_lexeme = tokenval;
    match(ID);
    emit(ID, id_lexeme);
    }
    else if (lookahead == NUM) {
    int num_value = tokenval;
    match(NUM);
    emit(NUM, num_value);
    }
    else
    error("syntax error in factor");
    }
    
    void match(int t)
    {
    if (lookahead == t)
    lookahead = lexan();
    else
    error ("syntax error in match");
    }
    /* error.c */
    
    void error(char* m) /* generates all error messages */
    {
    fprintf(stderr, "line %d: %s\n", lineno, m);
    exit(EXIT_FAILURE); /* unsuccessful termination */
    }
    /* main.c */
    
    int main(void)
    {
    FILE *fs, *ft ;
    char ch ;
    fs = fopen ( "d:\\source.txt", "r" ) ;
    if ( fs == NULL )
    { puts ( "Cannot open source file" ) ;
    exit(0 ) ; 
    }
    ft = fopen ( "d:\\out.txt","w" ) ; 
    if ( ft == NULL ) 
    { puts ( "Cannot open target file" ) ;
    exit(0 ) ; 
    } 
    
    
    init();
    parse();
    fclose(ft);
    fclose(fs);
    exit(0); /* successful termination */
    }
    
    
    
     
    Last edited by a moderator: Mar 13, 2011
  14. teacher

    teacher New Member

    Joined:
    Mar 27, 2011
    Messages:
    66
    Likes Received:
    8
    Trophy Points:
    0
    Occupation:
    i hate jobs
    Location:
    india,agra
    Home Page:
    http://www.crazylearner.in
    Both the source code have errors.They will not compile

    exit() .
    There must be one argument to exit function
    like exit(EXIT_SUCCESS) OR exit(EXIT_FAILURE) or exit(any_number) where any_number is between [0,255]

    you are also missing header file
    please include <stdlib.h> at the top
     
    Last edited: Apr 12, 2011
  15. teacher

    teacher New Member

    Joined:
    Mar 27, 2011
    Messages:
    66
    Likes Received:
    8
    Trophy Points:
    0
    Occupation:
    i hate jobs
    Location:
    india,agra
    Home Page:
    http://www.crazylearner.in
    Also there is a little syntax error at the end of 2 program .one closing bracket is missing.

    admins please correct this

    thank you
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice