windows C++下打开文件目录和创建

可以运行于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的头文件引用略有不同

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值