Tuesday 21 July 2015

C File Access-For hackers!

In the previous tutorial, Input and output in C we have talked about standard input and output devices handled by C programming language. Here we will discuss how to open , write, and close the files. we will see how C programmers can create, open, close text or binary files for their data storage. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices.

Consider a case, you hacked a system remotely and there is a text file which contains userID and password. you can't read without double clicking  on it. In this type of case where you have to read a file without physical contact, you need to write a program that reading contents of file. Here we will learn how to Opening Files, reading contents, writing, and close the file.

                                                        




Opening Files:
Before we start, let's understand an important data type FILE .
When accessing files through C, the first necessity is to have a way to access the files. For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. it points to structure that contains information about file, such as location of a buffer, weather the file is being read or written etc. but user don't need to know these details:
FILE *
You can think of it as the memory address of the file or the location of the file.
For example:
FILE *fp;

You can use the fopen( ) function to create a new file or to open an existing file:
FILE *fpoen(char *filename, char *mode);
Here filename is the C string containing the name of the file to be opened and mode is the C string containing a file access mode.
This function fopen() opens the filename pointed to, by filename using the given mode.  Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.
The access mode can have one of the following values:
Mode                 Description
r                open for reading
w                    open for writing (file need not exist)
                 open for appending (file need not exist)
r+                 open for reading and writing, start at beginning
w+                 open for reading and writing (overwrite file)
a+                 open for reading and writing (append if file exists)

If you are going to handle binary files then you will use below mentioned access modes instead of the above mentioned:
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
Upon successful completion, fopen() shall return a pointer to the object controlling the stream. Otherwise, a null pointer shall be returned, and errno shall be set to indicate the error.
Here's a simple example:
FILE *fd;
fd=fopen("usernameandpassword.txt", "r");

After opening file, the next thing to do is to read or write the file. There are several ways provided by C, of wich getc and putc are the simplest. The two functions getc() and putc() are the most basic functions of C. They are used to read the character and to display the character.

Reading a File:
The function getc() reads a character from a file referenced by file pointer opened in read mode using fopen():
int getc(FILE *fd);
Here fd is the pointer to a FILE object that identifies the stream on which the operation is to be performed. getc() returns the next character on the given input stream and increments the stream's file pointer to the next character. It reaches EOF marker after reaching the end of  file.

There are another functions for read a file:
1. fgetc() :
fgetc() function to read a single character from a file:
int fgetc( FILE * fd );
The fgetc() function reads a character from the input file referenced by fd.
fgetc() and getc() are equivalent except that if getc() is a macro, it may evaluate fd more than once.
2. fgets() :
char *fgets( char *buf, int n, FILE *fd );
The functions fgets() reads up to n - 1 characters from the input stream referenced by fd. It copies the read string into the buffer buf, appending a null character to terminate the string.

Writing a File:
putc is an output function:
int putc(int c, FILE *fd);
putc writes the character c to the file fd and returns the character written, or EOF if an error occurs.

There are another functions for write a file:
1. fputc():
function to write individual characters to a stream:
int fputc( int c, FILE *fd );
The function fputc() writes the character c to the output stream referenced by fd.It returns the character written, or EOF for error.
2.fputs():
functions to write a null-terminated string to a stream:
int fputs( const char *s, FILE *fd );
The function fputs() writes the string s to the output stream referenced by fd. It returns a non-negative value on success, otherwise EOF is returned in case of any error.

getchar and putchar can be defined in terms of getc, putc, stdin, and stdout:
getchar() is equivalent to getc(stdin)
putchar(c) is equivalent to putc(c,stdout)

For formatted input or output of files, the function fscanf and fprintf may be used. These are identical to scanf and printf, except that the first argument is a file pointer that specifies the file to be read or written; the format string is the second argument :
int fscanf(FILE *fd, char *format, ...)
int fprintf(FILE *fd, char *format, ...)

Closing a File :
To close a file, use the fclose( ) function. The function:
int fclose(FILE *fd);
is the inverse of fopen; it breaks the connection between the file pointer and external name that was established by fopen, freeing the file pointer for another file.

Binary file I/O - fread and fwrite:
For binary File I/O you use fread and fwrite:
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);             
size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
Both of these functions deal with blocks of memories - usually arrays. Because they accept pointers, you can also use these functions with other data structures; you can even write structs to a file or a read struct into memory.

 If you like this post or have any question, please feel free to comment !

No comments:

Post a Comment

Blogger Widget