可以运行于Windows和Linux下:
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
78
79
|
#include "stdafx.h" //如果运行于Linux或UNIX下,需要注释这一句
#if defined(WIN32) || defined(WIN64)
#include <io.h>
#include <direct.h>
#else
#if defined(linux) || defined(_UNIX)
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#endif
#endif
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using
namespace
std;
void
WriteHello(fstream &f)
{
f <<
"hello,world!!"
<< endl;
}
int
main(
void
)
{
char
dir[]=
"123/"
;
char
fname[]=
"123//123.txt"
;
string buf;
vector<string> str_arr;
#if defined(WIN32) || defined(WIN64)
cout<<
"It is in Windows OS!"
<<endl;
if
(_access(dir,0)) {
cout <<
"文件夹不存在!!"
<< endl;
_mkdir(dir);
//windows下创建目录
}
else
cout <<
"文件夹存在"
<< endl;
#else
#if defined(linux) || defined(_UNIX)
cout<<
"It is in linux OS!"
<<endl;
if
(access(dir,0)==-1) {
if
(mkdir(dir,0777))
//Linux和UNIX下创建目录
cout <<
"create directory '123' failed!!!"
<< endl;
else
cout <<
"create directory '123' successfully!!"
<< endl;
}
#endif
#endif
fstream f1;
f1.open(fname, ios::in);
if
(!f1) {
f1.close();
f1.open(fname, ios::out);
//如果没有文件123.txt,则创建它
WriteHello(f1);
f1.close();
}
else
{
do
{
//如果文件123.txt存在,则打开它
f1>>buf;
str_arr.push_back(buf);
//将文件的一行文本内容读入动态数组
cout << buf << endl;
//显示文件的一行
}
while
(!f1.eof());
cout <<
"-----End-----"
<< endl;
f1.close();
int
size=str_arr.size();
for
(
int
i=0; i<size; i++) {
if
(str_arr[i]==
"你好"
)
//如果当前行是"你好",则在末尾添加"!!!"
str_arr[i]+=
"!!!"
;
}
f1.open(fname, ios::out|ios::trunc);
for
(
int
i=0; i<str_arr.size(); i++) {
f1 << str_arr[i] << endl;
cout << str_arr[i] << endl;
}
WriteHello(f1);
//在文件末尾添加Hello world
f1.close();
}
return
0;
}
|
Windows和Linux下的文件夹判断和创建不一样,所以只有采用条件宏进行代码编写,代码复杂了点。
代码已经在Win8的VS2012和Ubuntu 13.04下调试运行通过。
我手头没有UNIX,无法调试,如果在UNIX下,估计和Linux的头文件引用略有不同