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.
#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













