Reading and writing formatted I/O in C.
Source listing
//------------------------------------------------------
// File: Code602_FileIO.cpp
// Purpose: Demonstration of formatted I/O in ANSI Standard C
// Programming Language: C
// Author: Dr. Rick Coleman
//---------------------------------------------------------------
#include <stdio.h>
#include <string.h>
int main(void)
{
int inum;
float fnum;
char string[81];
FILE *fptr;
fptr = fopen("textfile.txt", "w");
//-----------------------------------------------------------
// Writing formatted data to a file
// I/O function: int fprintf(File *fptr, char *format,...)
//-----------------------------------------------------------
do
{
printf("Type int, float, and string: ");
scanf("%d %f %s", &inum, &fnum, string);
fprintf(fptr,"%d %f %s\n",inum,fnum,string);
}
while (inum != 0);
fclose(fptr);
//-----------------------------------------------------------
// Reading formatted data from a file
// I/O function: int fscanf(File *fptr, char *format,...)
//-----------------------------------------------------------
if((fptr=fopen("textfile.txt","r"))==NULL)
{
printf("Can't open textfile.txt.\n");
return 0;
}
while(fscanf(fptr,"%d %f %s", &inum, &fnum, string) != EOF)
printf("%d %f %s\n",inum,fnum,string);
fclose(fptr);
return 0;
}