Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to handle integer data files using file concepts
In C, file handling allows us to work with different types of data including integers. This program demonstrates how to read integer data from one file and separate odd and even numbers into different files using file concepts.
Syntax
FILE *fopen(const char *filename, const char *mode); int putw(int w, FILE *stream); int getw(FILE *stream); int fclose(FILE *stream);
Approach
The program follows these steps −
- Create a DATA file and write integers to it
- Read integers from DATA file
- Separate odd numbers into ODD file and even numbers into EVEN file
- Display contents of both ODD and EVEN files
Example
Note: This example involves file operations. Since online compilers may have restrictions on file creation, the output shown represents expected behavior on a local system.
#include <stdio.h>
int main() {
FILE *f1, *f2, *f3;
int number, i;
/* Step 1: Create DATA file and write numbers */
printf("Creating DATA file with numbers 1 to 10<br>");
f1 = fopen("DATA", "w");
if (f1 == NULL) {
printf("Error: Cannot create DATA file<br>");
return 1;
}
for (i = 1; i <= 10; i++) {
putw(i, f1);
}
fclose(f1);
/* Step 2: Read from DATA file and separate odd/even */
f1 = fopen("DATA", "r");
f2 = fopen("ODD", "w");
f3 = fopen("EVEN", "w");
if (f1 == NULL || f2 == NULL || f3 == NULL) {
printf("Error: Cannot open files<br>");
return 1;
}
while ((number = getw(f1)) != EOF) {
if (number % 2 == 0)
putw(number, f3); /* Write to EVEN file */
else
putw(number, f2); /* Write to ODD file */
}
fclose(f1);
fclose(f2);
fclose(f3);
/* Step 3: Display contents of ODD and EVEN files */
f2 = fopen("ODD", "r");
f3 = fopen("EVEN", "r");
printf("Contents of ODD file:<br>");
while ((number = getw(f2)) != EOF)
printf("%3d", number);
printf("\nContents of EVEN file:<br>");
while ((number = getw(f3)) != EOF)
printf("%3d", number);
fclose(f2);
fclose(f3);
return 0;
}
Output
Creating DATA file with numbers 1 to 10 Contents of ODD file: 1 3 5 7 9 Contents of EVEN file: 2 4 6 8 10
Key Points
- putw() writes an integer to a binary file
- getw() reads an integer from a binary file
- Always check if file operations succeed by verifying file pointers are not NULL
- Close all opened files to free system resources
- The modulo operator (%) determines if a number is odd or even
Conclusion
This program demonstrates effective file handling in C for integer data processing. It shows how to create, write, read, and separate data across multiple files using standard file operations.
Advertisements
