#include <stdio.
h>
#include <stdlib.h>
int main()
{
// file pointer variable to store the value returned by fopen
FILE* fptr;
// Array to store the content read from the file
char content[100];
// Open the file in read mode
fptr = fopen("a.txt", "r");
printf("Enter the string");
scanf("%s",&content);
// Read the content from the file and store it in the 'content' array
//gets(content, 1000, fptr);
// Print the content of the file
printf("Content of the file:\n%s", content);
// Close the file after reading
fclose(fptr);
// Pause to keep the console window open
getchar(); // Wait for a key press before closing the program
return 0;
}
2.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fptr;
int num;
char str[20];
// Open the file in read mode
fptr = fopen("a.txt", "r");
// Read an integer and a string from the file
//printf("Enter values for num and string");
//scanf("%d%s",&num,&str);
fscanf(fptr, "%d %s", &num, str);
// Print the values read from the file
printf("Number: %d\n", num);
printf("String: %s\n", str);
// Close the file
fclose(fptr);
return 0;
}
USGAE OF fseek(),ftell() and rewind()
#include <stdio.h>
int main() {
FILE *fptr;
char str[100];
// Open file in read-write mode
fptr = fopen("a.txt", "r+");
// Move to the 10th byte of the file
fseek(fptr, 10, SEEK_SET);
// Read from that position
fgets(str, 100, fptr);
printf("Read string: %s\n", str);
int position = ftell(fptr);
printf("Current position in file: %d\n", position);
// Read the first 10 characters
fgets(str, 10, fptr);
printf("First 10 characters: %s\n", str);
// Use rewind to reset the file pointer to the beginning
rewind(fptr);
// Read again from the beginning
fgets(str, 10, fptr);
printf("First 10 characters after rewind: %s\n", str);
// Close the file
fclose(fptr);
return 0;
}
OUTPUT:
File content = chaitra gowda hiii
LAB PROGRAM
9.Write a C program to create two files to store even and odd numbers.
#include <stdio.h>
int main() {
FILE *evenFile, *oddFile;
int num;
// Open the files for writing
evenFile = fopen("even.txt", "w");
oddFile = fopen("odd.txt", "w");
// Generate numbers from 1 to 100 and classify them
for (num = 1; num <= 100; num++) {
if (num % 2 == 0) {
// If number is even, write to the even numbers file
fprintf(evenFile, "%d\n", num);
} else {
// If number is odd, write to the odd numbers file
fprintf(oddFile, "%d\n", num);
}
}
// Close the files
fclose(evenFile);
fclose(oddFile);
printf("Even and odd numbers have been written to separate files.\n");
return 0;
}