COM 102- COMPUTER PROGRAMMING AND DATA STRUCTURES-(2+1). 1. Ex. No.: 16. File I/O. Date: Aim: o To make use of file I/O
COM 102- COMPUTER PROGRAMMING AND DATA STRUCTURES-(2+1)
Ex. No.: 16
File I/O
Date:
Aim: o
To make use of file I/O in the C program.
Example 1: Write to a text file using fprintf(). Source Code: #include int main() { int num; FILE *fptr; fptr = fopen("program.txt","w"); if(fptr == NULL) { printf("Error!"); exit(1); } printf("Enter an integer number:"); scanf("%d",&num); printf("Open the file program.txt and check the entered number in that file"); fprintf(fptr,"%d",num); fclose(fptr); return 0; }
1
COM 102- COMPUTER PROGRAMMING AND DATA STRUCTURES-(2+1)
Example 2: Read from a text file using fscanf(). Source Code: #include int main() { int num; FILE *fptr; if ((fptr = fopen("program.txt","r")) == NULL) { printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); } fscanf(fptr,"%d", &num); printf("Value of n=%d", num); fclose(fptr); return 0; }
2
COM 102- COMPUTER PROGRAMMING AND DATA STRUCTURES-(2+1)
Example 3: Reading and Writing to File using fprintf() and fscanf(). Source Code: #include struct emp { char name[10]; int age; }; int main() { struct emp e; FILE *p,*q; p = fopen("one.txt", "a"); q = fopen("one.txt", "r"); printf("Enter Name and Age:"); scanf("%s %d", e.name, &e.age); fprintf(p,"%s %d", e.name, e.age); fclose(p); do { fscanf(q,"%s %d", e.name, e.age); printf("%s %d", e.name, e.age); } while(!feof(q)); return 0; } Do it yourself by writing a C program for the following Create a data file a series of integer numbers, read these numbers and then write all odd and even numbers separately to two other files. Create a random access file that could store details about five products.
3