One line reads a text file

Source: Internet
Author: User
The following is an example. It reads the first line of autoexec. bat.
# Include <stdio. h>
# Include <stdlib. h>

Main ()
{
File * FP;
CharS [256];
If(FP = fopen ("C: // autoexec. Bat", "R") = NULL)
{
Printf ("can't open file/N ");
Return;
}
Fgets (S, 256, FP );
Printf ("line1: % s/n", S );
Fclose (FP );
}
// The combination of file stream and string is the best:
# Include <iostream>
# Include <fstream>
# Include <strstream>
# Include <string>
Using namespaceSTD;

IntMain ()
{
String line;
Ifstream input ("input.txt", IOS: In );
Strstream temp;

While(1)
{
Getline (input, line );
If(Input. EOF ()) Break;
// A row of data has been stored in line and can be processed. Here, it is only output
Cout <line <Endl;
}
Input. Close ();

Return0;
}
Use get () and put ()

# Include <fstream. h>
Void main ()
{
Fstream file ("test_file.txt", IOS: Out | IOs: In | IOs: Binary );
Char ch;
Ch = 'O ';
File. Put (CH); // write ch content to the file
File. seekg (IOs: Beg); // locate the file header
File. Get (CH); // read one character
Cout <ch <Endl; // display it on the screen
File. Close ();
}
Use read () and write ()

# Include <fstream. h>
# Include <string. h>

Void main ()
{
Fstream file ("test_file.txt", IOS: Out | IOs: In | IOs: Binary );
File. Write (ARR, 5); // write the first five characters -- "hello" to the file.
File. seekg (IOs: Beg); // locate the file header
Static char read_array [100000], readone [1]; // here I will read some data
Int I = 0;
Do
{
File. Read (readone, 1); // read 1 Character
If (readone [0] ='s ')
{
...
}
I ++;
}
File. Close ();
}

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.