Show toolbar

2013年7月8日 星期一

Two ways to Read and Write Files

標題:C/C++兩種讀取文字檔的方法
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
//#include <iomanip>
//setprecision(4) "3.1415"
//setfill('Q') "QQ123"
//setw(5) " 123"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i = 0, j = 0;
const char *filePath = "pi.xls";
remove(filePath); //Delete File
//VC++ -----------------------------------------------------
//Write File
ofstream outputFile(filePath, fstream::app); //fstream::out fstream::app
if (outputFile.is_open()) //Check File
{
for(j=1;j<10;j++)
{
for(i=1;i<10;i++)
{
outputFile << i << "*" << j << "=" << i*j << "\t";
}
outputFile << endl;
}
outputFile.close();
}
//Read File
string lines = "";
ifstream inputFile(filePath);
if (inputFile.is_open()) //Check File
{
while(inputFile.good())
{
getline(inputFile, lines);
cout << lines << endl;
}
inputFile.close();
}
//Standard C -----------------------------------------------------
//Write File
FILE *writeFile = fopen(filePath, "a");
if (writeFile) { //Check File
for(j=1;j<10;j++)
{
for(i=1;i<10;i++)
{
fprintf(writeFile, "%d*%d=%d\t", i, j, i*j);
}
fprintf(writeFile, "\n");
}
fclose(writeFile);
}
//Read File
char line[100] = ""; // Light!!
FILE *readFile = fopen(filePath, "r");
if (readFile) { //Check File
while(fgets(line, sizeof(line), readFile))
{
printf("%s", line);
}
fclose(readFile);
}
return 0;
}
說明:
使用fstream的方法讀寫檔案,以及使用C的fopen讀寫檔案的方法。

沒有留言:

張貼留言