Enter some characters from the keyboard and send them to disk one after the other until the user enters a "#".
/*
Idea: Use the FGETC function to enter characters from the keyboard one by one, and then write to the disk file using the FPUTC function.
*/
The source program is as follows:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
Defines a pointer variable of type file
FILE *FP;
Char ch,filename[50];
printf ("Please enter the file name:");
scanf ("%s", filename);
Open the output file and make the FP point to the file
if ((Fp=fopen (filename, "w")) ==null)
{
If there is an error when opening, the output will not open information
printf ("Cannot open this file \ n");
If the open fails, the program terminates
Exit (0);
}
Used to receive the last input carriage return character
ch = getchar ();
printf ("Please enter a string ready to be stored to disk (end with # #);");
ch = getchar ();
while (ch!= ' # ')
{
Want to disk file output one character
FPUTC (CH,FP);
Display the output characters on the screen
Putchar (CH);
Then receive a character from the keyboard input
ch = getchar ();
}
Close File
Fclose (FP);
Want the screen to output a line break
Putchar (10);
return 0;
}
Note: The <run-time check Failure occurred during the first run #2-stack around the variable ' filename ' was corrupted> such errors, which were found after the inspection because
In the definition file name Char filename[10] array The number of lead is spent small (because when I enter, the Thing "f:\\file_1\\file.txt" at this time has exceeded the length of the file name array).
Sequential read and write data files (how to read and write characters to files)-examples