Tài liệu Đọc và ghi file text trong C++ ppt – Tài liệu text

Tài liệu Đọc và ghi file text trong C++ ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (326.91 KB, 9 trang )

Đọc và ghi file text trong C++
Trong C++ việc đọc và ghi file thường dùng để đưa các
bài toán ở dạng đầu vào và xuất ra kết quả. Điều này giúp
cho người ta dễ dàng kiểm tra xem chương trình của bạn
có thực sự đúng không khi cho chương trình chạy với
nhiều đầu vào và kiểm tra các kết quả ở đầu ra chương
trình có đúng với kết quả chuẩn. Bài viết này sẽ trình bày
các vấn đề về đọc và ghi file với các ký tự ASCII sử dụng
thư viện ifstream.
1. Sử dụng ofstream trong thư viện fstream để ghi file
– Cách ghi ra file sử dụng thư viện fstream cũng tương đối đơn giản, gần giống với cout<<
trong c++.
– Dưới đây là đoạn code đơn giản: tạo ra một file .txt rồi ghi vào đó một đoạn text mà mình
thích.
#include <iostream>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ofstream FileDemo (“File Demo.txt”);
FileDemo<<“Day la file demo su dung cach doc va ghi file su dung fstream”;
FileDemo.close();
return 0;
}
Khi chạy đoạn chương trình trên, chương trình sẽ tạo ra một file tên File Demo.txt nằm trong
cùng thư mục với project chứa code của bạn. Khi mở file này lên, bạn sẽ thấy đoạn text mà mình
muốn ghi trong đó.
– Và đây là một ví dụ về ghi ra các số chẳn từ 1 đến 1000 vào file “So Chan.txt”
#include <iostream>
#include <fstream>

#include <iostream>
using namespace std;
int main()
{
ofstream SoChan (“So Chan.txt”);
SoChan<<“Day so chan tu 1 -> 1000 \n”;
for(int a = 1; a <= 1000; a++)
{
if(a%2 == 0)
{
SoChan<<a;
SoChan<<“\n”;
}
}
SoChan.close();
1
return 0;
}
File “So Chan.txt ” sau khi chạy chương trình trên sẽ như hình bên dưới.
– Và tiếp tục một ví dụ ghi ra file “Ghi So Chan Le.txt” các số chẵn và lẽ từ 0 -> 100 (lưu
ý: ví dụ này được update sau theo yêu cầu một số bạn nên nên code không có màu).
#include <iostream>
#include <fstream>
#include <iostream>
using namespace std;
void ghiSoChan(ofstream &GhiSo)
{
int dem = 0;
GhiSo<<“Day so chan tu 1 -> 100 \n”;
for(int a = 1; a <= 100; a++)

{
if(a%2 == 0)
{
dem ++;
GhiSo<<a;
if(dem % 5 == 0)
{
GhiSo<<“\n”;
}
if(dem % 5 != 0)
{
GhiSo<<“\t”;
}
}
}
cout<<“\n So Chan: “<<dem;
}
void ghiSoLe(ofstream &GhiSo)
{
int dem = 0;
GhiSo<<“\nDay so le tu 1 -> 100 \n”;
for(int i = 1; i <= 100; i++)
{
if(i%2 != 0)
{
dem ++;
2
GhiSo<<i;
if(dem % 5 == 0)
{

GhiSo<<“\n”;
}
if(dem % 5 != 0)
{
GhiSo<<“\t”;
}
}
}
cout<<“\n So Le: “<<dem;
}
int main()
{
ofstream GhiSo(“Ghi So Chan Le.txt”);
ghiSoChan(GhiSo);
ghiSoLe(GhiSo);
GhiSo<<“\n ThanhCuong.wordpress.com”;
GhiSo.close();
system(“pause”);
return 0;
}
Kết quả file “Ghi So Chan Le.txt” thu được là:
3
– Như vậy cách ghi ra một file sử dụng thư viện fstream trong C++ là tương đối dễ dàng đúng
hông?
2. Sử dụng fstream trong C++ để dữ liệu đọc file
– Ở trên ta ghi ra một file “So Chan.txt” rồi, giờ ta thử đọc file đó trong C++ xem sao:
#include <iostream>
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
int a[501];
ifstream SoChan (“So Chan.txt”);
if(! SoChan.is_open())
{
cout<<“Khong the mo file.\n”;
return 0;
}
else {
for(int i = 1; i <= 500; i++)
{
4
SoChan>>a[i];
}
}
for(int i =1; i <= 500; i++)
{
cout<<a[i]<<” “;
}
SoChan.close();
system(“pause”);
return 0;
}
Và kết quả là:
– Và tiếp một ví dụ nữa cho các bạn hiểu hơn về các đọc file. Ví dụ này trình bày cách đọc một
ma trận như hình bên dưới từ file txt.
Và code chương trình như sau:
#include <iostream>
#include <fstream>

#include <iostream>
using namespace std;
int main()
{
5
int a[10][10];
int n;
ifstream MaTran (“Ma Tran.txt”);
if(! MaTran.is_open())
{
cout<<“Khong the mo file.\n”;
return 0;
}
else {
MaTran>>n;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
MaTran>>a[i][j];
}
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
cout<<a[i][j];
cout<<” “;
}

cout<<“\n”;
}
MaTran.close();
system(“pause”);
return 0;
}
– Và ví dụ tiếp theo, đọc một file text bằng fstream với C++.
#include<iostream>
#include<fstream>
using namespace std; int main() { ifstream stream1(“Text.txt”); char a[80]; if(!stream1) { cout
<< “Khong the mo file” << endl; } else { while(!stream1.eof()) { stream1 >> a; cout << a<<”
“; } } system(“pause”); return(0); }
6
– Như vậy qua 3 ví dụ về cách ghi ra file trong C++. Chúng ta thấy rằng thư viện fstream rất
hữu ích, những kiến thức về thư viện này nên tìm hiểu thêm tại cplusplus.com .
– Source code tìm một chuỗi trong file txt trên C++. Tải về source code bài này tại mediafire.
#include <iostream>
#include <fstream>
#include <string>
// thanhcuong.wordpress.com using namespace std;
int search();
int main (void)
{
search();
system(“pause”);
return 0;
}
int search()
{
fstream checkStream;

string searchString;
string lineOfText;
cout << “Nhap vao chuoi can tim: “;
getline(cin, searchString);
checkStream.open(“student.txt”, ios::in);
while (getline(checkStream, lineOfText))
{
getline(checkStream, lineOfText);
//if (checkStream.eof()) break; if (!checkStream) break;
if (lineOfText.find(searchString, 0) != string::npos)
{
cout<<“Tim thay chuoi: \””<<searchString<<“\” trong file.”<<endl;
7
return 1;
break;
}
}
checkStream.close();
cout << “Khong tim thay chuoi: “<<searchString<<” trong file.” << endl;
return 0;
}
– Source code đọc văn bản hiển thị trên chế độ text từ file “Text.txt”trên C++, và sử dụng
được các phím lên xuống, sang trái sang phải. Tại source code bài này tại mediafire.
#include<iostream>
#include<fstream>
#include <string.h>
#include <windows.h>
#include <conio.h>
#include <stdlib.h>
const int ESCAPE=27;

const int UP = 72;
const int DOWN = 80;
const int RIGHT = 77;
const int LEFT = 75;
using namespace std;
void curPos(int x, int y) {
HANDLE hStdout;
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
hStdout=GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hStdout, &csbiInfo);
csbiInfo.dwCursorPosition.X=x;
csbiInfo.dwCursorPosition.Y=y;
SetConsoleCursorPosition(hStdout, csbiInfo.dwCursorPosition);
}
int main()
{
int X;
int Y;
CONSOLE_SCREEN_BUFFER_INFO consoleinfo;
RECT rect;
HWND hwnd;
ifstream stream1(“Text.txt”);
char a[100];
int c;
if(!stream1)
{
cout << “Khong the mo file” << endl;
}
else {
while(!stream1.eof())

{
stream1 >> a;
cout << a<<” “;
}
8
}
while((c = getch()) != ESCAPE)
{
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
&consoleinfo);
X = consoleinfo.dwCursorPosition.X;
Y = consoleinfo.dwCursorPosition.Y;
if(c == LEFT)
{
curPos(X-1,Y);
}
if(c == RIGHT)
{
curPos(X+1,Y);
}
if(c == UP)
{
curPos(X,Y-1);
}
if(c == DOWN)
{
curPos(X,Y+1);
}
if(c == 71)
{

curPos(0,Y);
}
if(c == 79)
{
curPos(79,Y);
}
}
return(0);
}
3. Một vài lưu ý
– Tất cả các ví dụ trên IDE DevC++ có thể tải về tại sourceforge.
– Trong một số bài tập về tin học người ta thường yêu cầu ghi ra file “.output” và đọc file
“.input”, nếu gặp trường hợp đó, bạn làm tương tự như đối với file .txt. Tức là thay đổi tên file
ghi ra là “.output” và file đọc vào là “.input”.
– Mọi thắc mắc xin để lại comment bên dưới bài viết này. Mình sẽ trả lời trong thời gian sớm
nhất.
Và một điều quan trọng hơn:
Click vào đây để Download source code demo các ví dụ đọc và ghi bằng thư viện
fstream trong C++
– Tham khảo thêm bài viết Đọc & Ghi file trong C với ví dụ là các bài thi thực hành Tin Học
9

#include using namespace std;int main()ofstream SoChan (“So Chan.txt”);SoChan<<“Day so chan tu 1 -> 1000 \n”;for(int a = 1; a <= 1000; a++)if(a%2 == 0)SoChan< 100 (lưuý: ví dụ này được update sau theo yêu cầu một số bạn nên nên code không có màu).#include #include #include using namespace std;void ghiSoChan(ofstream &GhiSo)int dem = 0;GhiSo<<“Day so chan tu 1 -> 100 \n”;for(int a = 1; a <= 100; a++)if(a%2 == 0)dem ++;GhiSo< 100 \n”;for(int i = 1; i <= 100; i++)if(i%2 != 0)dem ++;GhiSo<#include #include using namespace std;int main()int a[501];ifstream SoChan (“So Chan.txt”);if(! SoChan.is_open())cout<<“Khong the mo file.\n”;return 0;else {for(int i = 1; i <= 500; i++)SoChan>>a[i];for(int i =1; i <= 500; i++)cout<#include #include using namespace std;int main()int a[10][10];int n;ifstream MaTran (“Ma Tran.txt”);if(! MaTran.is_open())cout<<“Khong the mo file.\n”;return 0;else {MaTran>>n;for(int i = 0; i < n; i++)for(int j = 0; j < n; j++)MaTran>>a[i][j];for(int i = 0; i < n; i++)for(int j = 0; j < n; j++)cout<#includeusing namespace std; int main() { ifstream stream1(“Text.txt”); char a[80]; if(!stream1) { cout<< “Khong the mo file” << endl; } else { while(!stream1.eof()) { stream1 >> a; cout << a<<”“; } } system(“pause”); return(0); }- Như vậy qua 3 ví dụ về cách ghi ra file trong C++. Chúng ta thấy rằng thư viện fstream rấthữu ích, những kiến thức về thư viện này nên tìm hiểu thêm tại cplusplus.com .- Source code tìm một chuỗi trong file txt trên C++. Tải về source code bài này tại mediafire.#include #include #include // thanhcuong.wordpress.com using namespace std;int search();int main (void)search();system(“pause”);return 0;int search()fstream checkStream;string searchString;string lineOfText;cout << “Nhap vao chuoi can tim: “;getline(cin, searchString);checkStream.open(“student.txt”, ios::in);while (getline(checkStream, lineOfText))getline(checkStream, lineOfText);//if (checkStream.eof()) break; if (!checkStream) break;if (lineOfText.find(searchString, 0) != string::npos)cout<<“Tim thay chuoi: \””<#include#include #include #include #include const int ESCAPE=27;const int UP = 72;const int DOWN = 80;const int RIGHT = 77;const int LEFT = 75;using namespace std;void curPos(int x, int y) {HANDLE hStdout;CONSOLE_SCREEN_BUFFER_INFO csbiInfo;hStdout=GetStdHandle(STD_OUTPUT_HANDLE);GetConsoleScreenBufferInfo(hStdout, &csbiInfo);csbiInfo.dwCursorPosition.X=x;csbiInfo.dwCursorPosition.Y=y;SetConsoleCursorPosition(hStdout, csbiInfo.dwCursorPosition);int main()int X;int Y;CONSOLE_SCREEN_BUFFER_INFO consoleinfo;RECT rect;HWND hwnd;ifstream stream1(“Text.txt”);char a[100];int c;if(!stream1)cout << “Khong the mo file” << endl;else {while(!stream1.eof())stream1 >> a;cout << a<<” “;while((c = getch()) != ESCAPE)GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),&consoleinfo);X = consoleinfo.dwCursorPosition.X;Y = consoleinfo.dwCursorPosition.Y;if(c == LEFT)curPos(X-1,Y);if(c == RIGHT)curPos(X+1,Y);if(c == UP)curPos(X,Y-1);if(c == DOWN)curPos(X,Y+1);if(c == 71)curPos(0,Y);if(c == 79)curPos(79,Y);return(0);3. Một vài lưu ý- Tất cả các ví dụ trên IDE DevC++ có thể tải về tại sourceforge.- Trong một số bài tập về tin học người ta thường yêu cầu ghi ra file “.output” và đọc file“.input”, nếu gặp trường hợp đó, bạn làm tương tự như đối với file .txt. Tức là thay đổi tên fileghi ra là “.output” và file đọc vào là “.input”.- Mọi thắc mắc xin để lại comment bên dưới bài viết này. Mình sẽ trả lời trong thời gian sớmnhất.Và một điều quan trọng hơn:Click vào đây để Download source code demo các ví dụ đọc và ghi bằng thư việnfstream trong C++- Tham khảo thêm bài viết Đọc & Ghi file trong C với ví dụ là các bài thi thực hành Tin Học