[C++] File operations (including special cases: spaces encountered in reading files are skipped, “files are only read once”)

author: & Carlton

tag: C++

topic: [C ++] file operations (includes special cases: spaces encountered in reading files are skipped, “files are only read once”)

website: Dark Horse Programmer C++

date: July 31, 2023

Directory

text file

write file

source code

file status

read file

source code

operation result

binary file

write file

source code

file status

read file

source code

Operation


Text file

write file

1. Reference file operation header file

2. Create a write-only file stream object

3. Open the file and specify the opening method

4. Write data

5. Close the file

Source Code

#include <iostream>
//1. Reference file operation header file
#include <fstream>
using namespace std;

void test01()
{
//2. Create a write-only file stream object
ofstream ofs;

//3. Open the file and specify the opening method
ofs.open("text.txt", ios::out);

//4. Write data
ofs << "Name: Zhang San" << endl;
ofs << "Gender: Male" << endl;
ofs << "Age: 18 years old" << endl;

//5. Close the file
ofs. close();
}


int main()
{
test01();
return 0;
}

File Status

(saved in the same lowest-level folder as the source file)

Note: there is a space between the colon and the text

Read file

The difference between the exit() function and the return() function

The exit() function accepts an integer parameter status, indicating the termination status of the program. Generally speaking, when the program terminates normally, it can return 0, indicating successful execution. Other non-zero status codes can be used to indicate different error or exception conditions.

Calling the exit() function immediately terminates program execution and does not execute any subsequent code. It will perform some cleanup work (such as closing files, freeing memory, etc.), and then directly return to the operating system.

It should be noted that Using the exit() function will skip the call of the destructor, so some resources may not be released correctly. Under normal circumstances, we should use the return statement to terminate the function or program to ensure the correct release of resources. The exit() function is typically used to terminate a program in case of a serious error or exception.

source code

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void test01()
{
ifstream ifs;

ifs.open("text.txt", ios::in);
if (!ifs.is_open())
{
cout << "Failed to open the file!" << endl;
return;
//or use exit(1);
/*
The exit() function accepts an integer parameter status, indicating the termination status of the program. In general, a program can return 0 when it terminates normally, indicating successful execution. Other non-zero status codes can be used to indicate different error or exception conditions.
Calling the exit() function immediately terminates program execution and does not execute any code after that. It will perform some cleanup work (such as closing files, freeing memory, etc.), and then directly return to the operating system.
It should be noted that using the exit() function will skip the call of the destructor, so some resources may not be released correctly. Under normal circumstances, we should use the return statement to terminate the function or program to ensure the correct release of resources. The exit() function is typically used to terminate a program in case of a serious error or exception.
*/
}

//read file
\t
//first way
    //The space is regarded as the end of the string, the single loop ends, and a newline is printed.
char buf1[1024] = { 0 };
while (ifs >> buf1)
{
cout << buf1 << endl;
}

//Second way
    //Take a newline character as the end of the string (spaces can exist as valid characters)
char buf2[1024] = { 0 };
while (ifs. getline(buf2, sizeof(buf2)))
{
cout << buf2 << endl;
}

//the third way
    //Take a newline character as the end of the string (spaces can exist as valid characters)
string buf3;
while (getline(ifs,buf3))
{
cout << buf3 << endl;
}

//the fourth way
    //Take a newline character as the end of the string (spaces can exist as valid characters)
char c;
while ((c = ifs. get()) != EOF)
{
cout << c;
}

ifs. close();
}

int main()
{
test01();
return 0;
}

Run result

The first way to read files:

A space is treated as the end of the string, and a newline is printed at the end of a single loop.

other methods:

A newline character is used as the end of the string (spaces can exist as valid characters)

In addition, it is noticed that all four methods of reading files are executed, but “the file is only read once”, because the file position identifier is not updated to the beginning of the file.

Binary files

Write file

Source code

#include <iostream>
#include <fstream>
using namespace std;

class Person
{
public:
char m_name[50];
int m_age;
};

void test01()
{
Person p = {"Zhang San",18};
ofstream ofs;
ofs.open("person.txt", ios::out | ios::binary);
ofs.write((const char*) & p, sizeof(p));
ofs. close();
}

int main()
{
test01();
return 0;
}

File Status

Read file

Source code

#include <iostream>
#include <fstream>
using namespace std;

class Person
{
public:
char m_name[50];
int m_age;
};

void test01()
{
ifstream ifs;
ifs.open("person.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "Failed to open the file!" << endl;
return;
}
Person p;
ifs.read((char*) &p, sizeof(p));
cout << "Name:" << p.m_name << endl;
cout << "age:" << p.m_age << endl;
ifs. close();
}

int main()
{
test01();
return 0;
}

Operation Status

Welcome to correct and share, thank you!