Sequential read and write data files (how to read and write characters to files)-examples

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.