C Programs to practice - File handling

     File is a collection of records. In c,we have a set file related operation. First, use an inbuilt structure "FILE" for accessing file related operations.

Next, create a file pointer for this structure "FILE". Further,use the following syntax to open a file.

filepointer= fopen("filename","mode");

where

filename is the file in which you are going to process.

mode refers the operation. 

"r"-Read the file.

"w"- Write the content to the file.

"a" -Read and write purpose.

Once the file is opened, write the contents to the test file until the last character by using a condition strlen(data)<0 followed by fputs() function.

When the condition fails,the control come out of the loop. Now, the program is finished.

Now, you can open the test file manually and check the content. The data you have written in the test file is shown.

The sample program is shown below.

"Filehandle.c"

 #include <stdio.h>

#include <string.h>

void main()

{

FILE *ft;

char data[50]=”Hello world, This is a sample program”;

ft=fopen(“test.c”,”w”);

if(ft==NULL)

{

printf(“test file fails to open”);

}

else

{

printf(“The file is opening”);

if (strlen(data)>0)

{

 fputs(data,ft);

fputs(“\n”,ft);

}

fclose(ft);

printf(“The file is written in file”);

getch();

}


The output is

Output screen of the "Filehandle.c"

The file is opening

The file is written in file

"test.c"

Hello world, This is a sample program.

Thus the way, we created file handling program in c.

No comments:

Post a Comment