fputs() and fwrite() function in C Language
The fputs() and fwrite() Function
The fputs() function is used to write string(array of characters) to the file and this function is declared in stdio.h header file.
Syntax
fputs(char str[], FILE *fp);
Example :-
The fputs() function takes two arguments, first is the string to be written to the file and second is the file pointer where the string will be written.
fwrite()
To write to a binary file, you need to use the function fwrite(). The functions takes four arguments: Address of data to be written in disk, Size of data to be written in disk, number of such type of data and pointer to the filed where you want to write.
Syntax
fwrite(address data,size data, numbers data, pointer to file);
Example :-
In this program, you create a new file in the C drive.
We declare a structure book with three variable- bookid, title, price and define it in the main function as b1.
Now, The first parameter takes the address of b1 and the second parameter takes the size of the structure book. Since, we're only inserting one instance of b1, the third parameter is 1. And, the last parameter fp pointer points to the file we're storing the data.
Finally, we close the file.
fread() function in C
Function fread() also take 4 arguments similar to fwrite() function as above.
Syntax
fread(address data, size data, numbers data, pointer to file);
Example :-
In this program, you read the same file and loop through the records one by one.
In simple terms, you read one book record of book size from the file pointed by fp pointer into the structure b1.
Comments
Post a Comment