The Program in C to Read a line of text from a file and Display it is given below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n;
printf("Enter the number of names: ");
scanf("%d", &n);
// Allocate memory for the names
char** names = (char**)malloc(n * sizeof(char*));
for (int i = 0; i < n; i++) {
names[i] = (char*)malloc(100 * sizeof(char));
}
// Read the names from the user
for (int i = 0; i < n; i++) {
printf("Enter name %d: ", i+1);
scanf("%s", names[i]);
}
// Open the file for writing
FILE* file = fopen("names.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write the names to the file
for (int i = 0; i < n; i++) {
fprintf(file, "%s\n", names[i]);
}
// Close the file
fclose(file);
// Create a copy of the file
FILE* file_copy = fopen("names_copy.txt", "w");
if (file_copy == NULL) {
printf("Error opening file copy!\n");
return 1;
}
// Write the names to the file
file = fopen("names.txt", "r");
char line[100];
while (fgets(line, 100, file)) {
fputs(line, file_copy);
}
// Close the file
fclose(file);
fclose(file_copy);
// Free the memory allocated for the names
for (int i = 0; i < n; i++) {
free(names[i]);
}
free(names);
return 0;
}
Output:
Enter the number of names: 3
Enter name 1: kumar
Enter name 2: aliz
Enter name 3: mukesh
//names_copy.txt// file is created
kumar
aliz
mukesh
Pro-Tips💡
This program prompts the user to enter the number of names, then uses a loop to read that many names from the user and stores them in an array of strings.
It then opens a file named “names.txt” in write mode using the fopen() function and writes each name to the file using the fprintf() function.
Next, it opens another file named “names_copy.txt” in write mode, reads the content of the “names.txt” file using the fgets() function,
and writes it to the “names_copy.txt” using the fputs() function. Finally, it closes both files and frees the memory allocated for the names.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.