In: Computer Science
Create a c file to read from an existing file one character at a time and print that character to the console
Create a c file to read a character from the standard input and write it to a file.
please help me
Code:
#include<stdio.h>
int main()
{
char ch;
FILE *file; //file pointer decleration
file=fopen("text.txt","r"); //open file in read
mode
if (file == NULL)
printf("Can not open file\n"); //could not open file
else // file open successfully
{
ch =fgetc(file); //read first charecter in ch
while(ch!=EOF) // run untill the last charecter of
file
{
printf("%c",ch);
//print charecter by charecter in console
ch=fgetc(file);
//point next charecter
}
}
fclose(file); //close the file
return 0;
}
text file:
Output:
2nd code to write char in file:
#include <stdio.h>
int main()
{
FILE *fptr; // creating a FILE variable
char ch; // creating a character variable
fptr = fopen("test.txt", "w"); // open the file in
write mode
printf("Enter a charecter\n");
scanf("%c",&ch); // take user input
putc(ch, fptr); // write character ch in file
printf("Write in file successfully");
fclose(fptr); // close the file
}
Output file:
Output: