Pages

Friday, December 3, 2010

Writing a file

Now that we have seen an example of how the files are read, let's see how we can write a file using the file handling functions. As I told you in earlier articles that if you are creating a new file or editing an existing file both are called "writing" in the context of file handling. Similar to reading a file, writing can also be done using various methods. It can be char by char writing, string by string or binary writing. Let's see all these methods of creating a file.

Writing a file - char by char

To write data in a file char by char, we will use the "fputc()" function. This function is just the opposite of the function we have studied in the last sessions "fgetc()" which reads a char at a time. "fputc" on the other hand "puts" (writes) a char to the file. To write multiple chars we can use this function in a loop. The "fputc()" takes two arguments the first argument is the char that we want to write and the second argument is the file pointer in which we want to perform the writing task.

Syntax
    fputc(char,file pointer)

Example
    fputc('G',fp); // Writes the alphabet G to the file pointed by fp
    fputc('?',fp); // Writes the symbol ? to the file pointed by fp
    fputc('3',fp); // Writes the digit 3 to the the file.
   
    char f='T';
    fputc(f,fp); // Writes the value of the variable f (which is T) to the file.


    As you can see in the above examples, the function fputc() is writing any char in the file. It can used to store any type of char - be it an alphabet, symbol or a digit. The last example, instead of writing the char directly to the file, first stores it in the variable "f" and then passes this as an argument to "fputc".


Example 1 - Writing a char to the file
#include
#include
void main()
{
    FILE *fp; // Line 1
    fp=fopen("test","w"); // Line 2
    char ch; // Line 3
    printf("\nWrite a character "); // Line 4
    scanf("%c",&ch); // Line 5
    fputc(ch,fp); // Line 6
    printf("\nSaved "); // Line 7
    fclose(fp); // Line 8
}



Description

Line 1 :
    Declares a variable of type FILE which is a must to handle files in C.
Line 2 :
    Using the "fopen()" we are creating a new file named "test". Did you see the change in the "mode". It has changed from "r"(reading) to "w" (writing). This means that we are telling the compiler that we want to open a file for "writing". As soon as this program is run, the compiler will create a new file named "test" in the same directory as the program. If there is an existing file with the same name it will be overwritten. There are options by which you change this behaviour which we will learn later on. In case you want to change the location of the file, you will have to write the path like this "c:/folder1/folder2/test". This will create a new file
named "test" inside folder2 which is a sub folder of folder1. You can also add an extension to the file name so that the OS recognizes the type of the file.
Line 3,4 and Line 5 :
In these two lines we are asking the user to enter the character that has to be stored in the file. The user's value has been saved in the variable "ch". As we know that a char can save any type of char as long as it is of single length, anything that the user enters will get saved in the variable "ch".
Line 6:
Once the data is there in the variable "ch", now comes the writing part. The "fputc()" will write the value of "ch" to the file pointed by "fp" (test).
Line 7:
    Informs the user that the data has been saved.(optional)
Line 8 :
    Closes the file.


Let's create another program using "fputc()" to write multiple chars in the file.


Example 2 - Writing multiple chars to a file

#include
#include // For strlen
#include
void main()
{
    FILE *fp; /// Line 1
    fp=fopen("myfile.txt","w"); // Line 2
    char str[20]; // Line 3
    printf("\nWrite a string "); // Line 4
    gets(str); // Line 5
    for (int i=0;i
        fputc(str[i],fp); // Line 7
    printf("\nSaved a string."); // Line 8
    fclose(fp);
}

Description

Line 3 :
    Declares a string named "str", with a size of 20. You change it to any size that you want.
Line 5:
    We have used "gets()" instead of "scanf()" so that the user can enter spaces in the string.
Line 6:
    Since "fputc()" can not write more than one char at a time, we have written "fputc()" inside the loop which runs as per the length of the string. Assuming that the user enters "C Programming" in line no 2, the loop will enter the char at the "i"th position in the file. The char "C" will be entered first followed by space, 'P','R','O','G','R','A','M','M','I','N','G'. Although the code will save all the characters of the string in the file, even then it won't be correct to say that "fputc()" can write a string to the file. "fputc()" can write only a single char at a time. Therefore like "fgetc()" it is also not suitable for writing large strings.

0 comments:

Post a Comment