Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++ 读写二进制文件 read write binary file #32

Open
Shellbye opened this issue Sep 13, 2018 · 0 comments
Open

C++ 读写二进制文件 read write binary file #32

Shellbye opened this issue Sep 13, 2018 · 0 comments
Labels

Comments

@Shellbye
Copy link
Owner

Shellbye commented Sep 13, 2018

对于我这种C++新人来说,用C++干个啥都很困难,似乎都需要记录。比如近日有这么一个需求,把一个二进制文件(old.wav)读取到内存里,返回给调用方,然后调用方在把它写入到一个新的二进制文件(new.wav)中。

#include <iostream>
#include <vector>
#include <fstream>


std::vector<char> read_return() {
    std::ifstream file("old.wav", std::ios::binary | std::ios::ate);
    std::streamsize size = file.tellg();
    file.seekg(0, std::ios::beg);
    std::vector<char> buffer(size);
    if (file.read(buffer.data(), size)) {
        std::cout << "Read OK!" << std::endl;
        return buffer;
    } else {
        std::cout << "Read Failed!" << std::endl;
        return buffer;
    }
}

int main() {
    auto wav = read_return();
    
    std::ofstream stream("save.wav", std::ios::binary);
    stream.write((const char *) &wav[0], wav.size());
    stream.close();
    return 0;
}

参考:

  1. https://stackoverflow.com/questions/18816126/c-read-the-whole-file-in-buffer
  2. http://www.cplusplus.com/forum/beginner/76436/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant