Lab 17
Lab 17
md 2024-11-10
Example 01: C Program to read from console & write data into file.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 1000
int main()
{
char str[MAX_SIZE];
Example Input:
Enter a sentence : Always do right. This will gratify some people and
astonish the rest.
1/4
lab17.md 2024-11-10
int main()
{
/* File pointer to hold reference to our file */
FILE *fPtr;
char str[MAX_SIZE];
int len = 0;
/*
* Open file in r (read) mode.
* "data/example.txt" is complete file path to read
*/
fPtr = fopen("data/exaple.txt", "r");
printf("%s\n", str);
}
return 0;
}
2/4
lab17.md 2024-11-10
Example 03: C program to take N student informtion as input from the console and saves it into a
text file
#include <stdio.h>
struct Student
{
char fname[SIZE];
char lname[SIZE];
int id;
float cgpa;
};
int main()
{
int num_students;
char filename[SIZE];
printf("\nEnter the filename to save the data: ");
scanf("%s", filename);
3/4
lab17.md 2024-11-10
}
fclose(fp);
printf("Student data saved to %s successfully!\n", filename);
return 0;
}
Example 04 : C program that reads the saved student data from the previous example and
displays it on the console.
#include <stdio.h>
#define SIZE 100 // Adjust this value as needed
struct Student
{
char fname[SIZE];
char lname[SIZE];
int id;
float cgpa;
};
int main()
{
char filename[SIZE];
printf("Enter the filename containing student data: ");
scanf(" %s", filename);
4/4