Friday 30 June 2017

File Read and Write


Types of Files
 - Text Files: normal .txt files
 -  Binary files: the .bin files, store it in the binary form (0's and 1's).  
 
For reading and writing to a text file, we use the functions fprintf() and fscanf().
fscanf(fptr,"%d", &num);
fprintf(fptr,"%d",num);
For Reading and Writing line by line, use fgets, fputs   
while(fgets(buffer, MAX_LINE_SIZE, inp_file_ptr))
{
 fputs(buffer, out_file_ptr);
 
Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files.
To write into a binary file, 
fwrite(address_data,size_data,numbers_data,pointer_to_file);
fwrite(&num, sizeof(struct threeNum), 1, fptr); 
To Read from binary file
fread(address_data,size_data,numbers_data,pointer_to_file);  
fread(&num, sizeof(struct threeNum), 1, fptr);

If you have many records inside a file and need to access a record at a specific position,
fseek(FILE * stream, long int offset, int whence)
// Moves the cursor to the end of the file 
fseek(fptr, sizeof(struct threeNum), SEEK_END);
  

No comments:

Post a Comment