码迷,mamicode.com
首页 > 其他好文 > 详细

文件操作

时间:2019-01-23 00:19:38      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:cpp   argc   操作   char s   ons   cstring   main   count()   int   

二进制文件写:

#include<iostream>
#include<fstream>

using namespace std;

int main(int argc, char const *argv[])
{
    if (argc != 3) {
        cout << "File name missing!" << endl;
        return 0;
    }
    ifstream inFile(argv[1], ios::binary|ios::in);
    if (!inFile) {
        cout << "Source file open error." << endl;
        return 0;
    }
    ofstream outFile(argv[2], ios::binary|ios::out);
    if (!outFile) {
        cout << "New file open error." << endl;
        inFile.close();
        return 0;
    }
    char c;
    while (inFile.get(c))
        outFile.put(c);

    outFile.close();
    inFile.close();
    
    return 0;
}

  

二进制文件读:

#include<iostream>
#include<fstream>
#include<cstring>

using namespace std;

class CStudent {
public:
    char szName[20];
    int nScore;
};

int main()
{
    CStudent s;
    ifstream InFile("students.dat", ios::out|ios::binary);
    if(!InFile) {
        cout << "error" << endl;
        return 0;
    }
    while (InFile.read((char*)&s, sizeof(s))) {
        int nReadedBytes = InFile.gcount();
        cout << s.szName << " " << s.nScore << endl;
    }
    InFile.close();
    return 0;
}

  

二进制文件修改:

#include<iostream>
#include<fstream>
#include<cstring>

using namespace std;

class CStudent {
public:
    char szName[20];
    int nScore;
};

int main()
{
    CStudent s;
    fstream iofile("students.dat", ios::in|ios::out|ios::binary);
    if(!iofile) {
        cout << "error" << endl;
        return 0;
    }
    iofile.seekp(2*sizeof(s), ios::beg);
    iofile.write("Mike", strlen("Mike")+1);
    iofile.seekg(0, ios::beg);
    while (iofile.read((char*)&s, sizeof(s))) {
        int nReadedBytes = iofile.gcount();
        cout << s.szName << " " << s.nScore << endl;
    }
    iofile.close();
    return 0;
}

  

文件拷贝:

#include<iostream>
#include<fstream>

using namespace std;

int main(int argc, char const *argv[])
{
    if (argc != 3) {
        cout << "File name missing!" << endl;
        return 0;
    }
    ifstream inFile(argv[1], ios::binary|ios::in);
    if (!inFile) {
        cout << "Source file open error." << endl;
        return 0;
    }
    ofstream outFile(argv[2], ios::binary|ios::out);
    if (!outFile) {
        cout << "New file open error." << endl;
        inFile.close();
        return 0;
    }
    char c;
    while (inFile.get(c))
        outFile.put(c);

    outFile.close();
    inFile.close();
    
    return 0;
}

  

 

文件操作

标签:cpp   argc   操作   char s   ons   cstring   main   count()   int   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/10306557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!