May 14, 2008

Simple C File Handling In Action - Small code snipet which covers most of basic file handling and navigat

Free Web Hosting, No Ads > CONTRIBUTE > Computers > Programming Languages > C/C++ Programming

free web hosting

Simple C File Handling In Action - Small code snipet which covers most of basic file handling and navigat

Nitin Mangi
Yesterday I suddenly got a lot of work. The same work we try to push off, yes you are right all formalities to get the code review incorporated and update all source code files with code review headers.

Imagine if you need to open 300 files one by one and append code review headers at the end.

Since most files are reviewed in groups of 20 to 30 files. We require one header to be placed in say 20 to 30 files.

To simplify I went back to my class assignment days and wrote this small c utility to open all files passed on command line and open attach code review headers and close them.

We also need to checkout and check in from source control application, but that’s easy scripts.
So just plugged in this utility in batch file and complete the tiring work in seconds.

Its simple c file handling in action. I thought of posting it here for my friends who want to learn c file handling most features in a very small program.

Or for somebody like me who requires to complete his code reviews and is lazy enough to write this. So it’s all action.

Its simple you can just modify this skeleton as you like it.

CODE

#include "stdio.h"
#include "stdlib.h"

int main(int argc, char* argv[])
{    
    /* pointers to file for writing and file containg the header */
    FILE * fpWrite;
    FILE * fpReviewHeader;
    /* size of file and header */
    long lSizeOfHeader = -1;
    long lSizeOfFile = -1;
    /* buffer to keep the header to be appended */
    char * buffer;

    /* at least one file must be passed */
    if( argc < 2 )
    {
        printf("\nUsage: acrh <filename>\n");
    }

    /* open file have the header in read and binary mode
       you make like to take this also from command line also.
       This file starts with a new line character used
       in case the file where header will be appended does
       not have new line character in the end */
    fpReviewHeader=fopen("c:\\temp\\review.txt", "rb");

    /* get the file size */
    fseek (fpReviewHeader , 0 , SEEK_END);
    lSizeOfHeader = ftell (fpReviewHeader);
    rewind (fpReviewHeader);
    
    /* allocate memory to contain the whole header file.*/
    buffer = (char*) malloc (lSizeOfHeader);
    
    /* read the file into the buffer. */
    fread (buffer,1,lSizeOfHeader,fpReviewHeader);    
    
    /* get all the file names passed on the command line*/
    for(int i=1;i<argc;++i)
    {
        /* open the each file in append and binary mode */
        fpWrite=fopen(argv[i], "ab+");
        /* here we get the size of the file and check if the
           second last character is new line character    */
        fseek (fpWrite , 0 , SEEK_END);
        lSizeOfFile = ftell (fpWrite);
        rewind (fpWrite);
        fseek (fpWrite , lSizeOfFile-2 , SEEK_SET);
        int aChar = fgetc(fpWrite);
        fseek (fpWrite , 0 , SEEK_END);
        /* if no newline is there we append the original buffer with new line    */
        if( aChar != 13 )
        {
            fwrite(buffer,1,lSizeOfHeader,fpWrite);            
        }
        /* remove the newline character from buffer */
        else
        {
            /* write the block header to file */
            fwrite(buffer+2,1,lSizeOfHeader-2,fpWrite);        
        }
        printf("\nUpdated: %s",argv[i]);
        /* this flushes the data from cache to file */
        fflush(fpWrite);
        /* close this file */
        fclose(fpWrite);
    }
    /* close the header file */
    fclose(fpReviewHeader);
    /* free the header buffer */
    free(buffer);

    return 0;
}


Enjoy smile.gif

 

 

 


Reply

jmb2006
cool, im learning c myself, how long did it take you to write that code? also what websites did you learn from, decent websites for c programming beginners? thanks.

Reply

Trap FeedBacker
file programs in c
Simple C File Handling In Action

Actually I m selected for 3rd round in cmy.
In technical round they ask to write some program in file concept in c, malloc and c alloc program so I need some programs which are used to write in technical round

-reply by pavithra

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Recent Queries:-
  1. learn file handling - 5.55 hr back.
  2. c program file handling - 7.62 hr back.
  3. c file handling - 9.73 hr back.
  4. local file handling control - 11.67 hr back.
  5. programming for file handling in c - 11.81 hr back.
  6. sample programs on file handling in c - 24.98 hr back.
  7. simple file handling in c - 37.97 hr back.
Similar Topics

Keywords : simple, c, file, handling, action, small, code, snipet, covers, basic, file, handling, navigat

  1. Most Efficient Code To Get Prime Numbers
    (6)
  2. C++ Roman Numeral Conversion Code Help
    If-else Problem (5)
    thanks....
  3. Buffer Overflow In Action Tutorial
    Learn how to buffer overflow programs to change the program flow... (0)
    This tutorial will show you how to buffer overflow programs in order to change the flow of the
    application , even if this means executing your own code. A very well explained tutorial of buffer
    overflows ( not theory but practise ) + a 20 min video tutorial/demonstration + all the files needed
    for the tutorial.. Buffer Overflow In Action Tutorial LINK ....
  4. A Telephone Directory Source Code In C
    (2)
    Well i had made this project some years before. It is a telephone directory which has a very good
    User Interface operatable with scroll key. This code can be usefull in learning about file handling
    and User Interface. CODE #include <stdio.h> #include <box.h> #include
    <conio.h> #include <dos.h> #include <stdlib.h> #include <bios.h>
    #include <graphics.h> FILE *fp; addnew2(char [],char []);
    prnd(); deleteit(); info(); pl(); checkcmd();
    showall(....
  5. Encrypting A File
    (5)
    Well we all know that encrypting in C is not difficult task since we have access to low level
    programming.. Now to encrypt a simple text file we can have the following procedure Just read a
    single character from a file and then change its value with a valid algorithm and then write it to
    some other file which wil become the encrypted version of the file. An Example: a file has in it the
    following text "Love". Now all we need to do is get the ascii code for it and then add 7 to it and
    then write it to the other file. this way the file will get encrypted. I have a code wh....
  6. Wolfenstein Source Code Now In Public Domain
    (3)
    the Wolfenstein game which we enjoy it alot becouse of its highly graphic technique now u can
    learn alot from it and become profissional programer becouse now its source code in Public Domain
    get the source code now and make your way to become profissional programer get it at
    Wolfenstein source code ....
  7. File Format Encyclopedia Release 1.00
    (2)
    File Format Encyclopedia is FREEWARE so you can copy, read, use it freely but you can't modify
    it in any way!!!File Formats Encyclopedia A MUST HAVE for professional programmers!
    Over 300 formats layouts including: graphics,sound, animation, mods, database, text,executables,
    communication and much more ....
  8. Source Code For Paint Like Program Under Dos In C
    (2)
    this is a dos program that you have been waiting for you learn from it you how to do graphic
    programing under dos if you understand it your then will be able to do any kind of windows GUI in
    dos it make icons and use them it deal with graphic file youwill also learn how to use mouse have
    nice time ....
  9. Prob With My C Code
    (4)
    Hi Guys! this is a wonderful place.. although i wasnt a member till now i have referred to
    these forms quite a few times for my programming solns /biggrin.gif" style="vertical-align:middle"
    emoid=":D" border="0" alt="biggrin.gif" /> My problem is ::: I am writing a Code in C using
    Bloodshed Dev C++ 4.9.9.2 on Windows XP. I wanted to open an executable file from my code. After
    using the solution mentioned on these forums, I used QUOTE system("myprg"); It works
    fine.. But the prob is that i want my C program to execute this command and then return to t....
  10. Handling Byte Streams
    (2)
    I am writing a program that needs to read/write to blocks on a floppy disk. I am using two functions
    (written by someone else) that are defined as follows: Code: CODE int WriteBlock(int
    index, BYTE *buffer, int count); int ReadBlock(int index, BYTE *buffer, int count);
    I am making a call to ReadBlock() as follows: Code: CODE BYTE record_stream[512];
    ReadBlock(some_index,&record_stream,1); My problem is that when I compile I get the
    following error: Code: CODE no matching function for call to `disk::ReadB....
  11. Local File Time To File Time()
    (0)
    I'm working on sending some certain data to a server. Part of the process in gathering this data
    is done by using GetLocalTime() to get the current local time, this local time must then be
    converted to a FILETIME structure. I'm trying to get this done properly in Python, however my
    problem is that I do not know what my data will look like when the local time is converted to file
    time. I don't have the necessary compiler on my PC to test the code (for reasons I'm not
    going to waste time explaining, my main PC is temporarily unuseable and I'm using a mu....
  12. Storing Bit Values In A File
    (1)
    Hello All, I am developing a utility for zipping and unzipping a file using the Huffman Algorithm.
    The code is implemented using 'C' language. I have finished coding for generating the
    appropriate bit code values for each of the symbols present in file and my next objective is to
    store the bit code values in a seperate file. As you all are aware, the smallest data type that is
    supported by C is the character which is 1 byte. Please can anybody suggest me on how to store the
    bit values generated as codes in a file? Thanks. ....
  13. Code Documentation
    A better way? (1)
    This is not so much a question, actually, but a bit of a plug for an interesting tool I've
    discovered recently. Anyway. How does everyone else document their code? Are in-source comments
    sufficient? Do you write extra detailed documentation outside of the code? Or do you generate
    external documentation from the code? Since I've been doing Java recently, I was in awe when I
    discovered javadoc. An incredible tool that allows you to generate external documentation for your
    code from your comments in-source. The syntax is reasonably simple, allowing the comme....
  14. Reactions To A Busy File
    (2)
    I just wanted to know if let's say you have a file called tempfile.dat and it is being used by
    dozens of parts of a script to transfer data, what happens if both scripts run at the same time and
    use the tempfile? will it throw a text file is busy error or will it patiently wait until a script
    is done using it before it uses it? Because if i send information to the tempfile, then close it,
    then reopen it again to transfer back the information, I don't want the other script to start
    using it in the middle of that sequence or the results will be catastrophic. Any ....
  15. Adding Myfileexists Function To My Basic Code?
    (2)
    Here is a short and basic piece of my first ever application written in Visual C++ 6.0 . I have also
    commented the code well to show you EXACTLY what my code is meant to do with each function. What
    exactly I am asking for, is for someone to please replace anywhere that you see "EXISTS" with the
    proper function "myFileExists" to actually check to see if the file exists. Also I am asking for
    anyone that may see an error in this code, to please point it out to me and how I can fix it. If
    anyone can help me with getting this very basic code to work, it would be GREATLY appr....
  16. Weird Characters Appending To File
    (2)
    Anytime I open a file and close it without changes, weird characters show up. Here is the code:
    PHP Code: inFile = fopen("serefs.dat","rb"); outFile = fopen("tempfile.dat","wb"); while
    (!feof(inFile)) { char line ; char timeline ; fgets(line,512,inFile);
    strncpy(timeline, line, 10); timeline = '\0'; int filetime;
    filetime = atoi(timeline); if(filetime > (realtime - 86400)) {
    fputs(line,outFile); } } fclose(inFile); fclose(outFile); //Put tempfile in buffe....
  17. C Code, Can U Solve This?
    Another interesting problem (22)
    Hello, Look at the code given below CODE void fun(void) { /* Put your code here so
    that main does not print 20 */ } int main() { int i = 20; fun();
    printf("i = %d\n", i); return 0; } 1. You are allowed to put your code
    ONLY in fun. 2. You are not allowed to change even one character in main. 3. You should not use
    functions like exit(),abort() in the function fun. How do I manipulate and change the value of i?
    Have fun.......
  18. Where Can I Get Full Souce Code Of Turbo C++ ?
    where can i get full souce code of Turbo (2)
    where can i get full souce code of Turbo C++ ? Al... it must be complete... complete... includes and
    libraries... all.. pls.. help me.. coz i cant compile my programs........
  19. Running An Extenal File
    how to (3)
    hi guyz i fairly new to c++ i started readnig a big book but it gonna take me a while to reach the
    last page and i need to do a menu quite fast so could any one of You help me with this
    /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" /> : i need to know
    whith action will run an external file using the the app assigned to it in the windows shell (sort
    of like the "run" command in used in dos) or a brief source code with a button fireing some file to
    use as a tutorial /rolleyes.gif" style="vertical-align:middle" emoid=":rolleyes:"....

    1. Looking for simple, c, file, handling, action, small, code, snipet, covers, basic, file, handling, navigat

Searching Video's for simple, c, file, handling, action, small, code, snipet, covers, basic, file, handling, navigat
advertisement



Simple C File Handling In Action - Small code snipet which covers most of basic file handling and navigat



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE