所以我有這個程式,據說可以讀取任何檔案(例如影像、txt)并獲取其資料并使用相同的資料創建一個新檔案。問題是我想要陣列中的資料而不是向量中的資料,當我將相同的資料復制到 char 陣列時,每當我嘗試將這些位寫入檔案時,它都不會正確寫入檔案。
所以問題是我如何從中獲取資料std::ifstream input( "hello.txt", std::ios::binary );并將其保存,char array[]以便我可以將該資料寫入新檔案中?
程式:
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include <iterator>
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
FILE *newfile;
std::ifstream input( "hello.txt", std::ios::binary );
std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
char arr[buffer.size()];
std::copy(buffer.begin(), buffer.end(), arr);
int sdfd;
sdfd = open("newhello.txt",O_WRONLY | O_CREAT);
write(sdfd,arr,strlen(arr)*sizeof(char));
close(sdfd);
return(0);
}
uj5u.com熱心網友回復:
試試這個:(
它基本上使用了一個字符*,但這里是一個陣列。在這種情況下,你可能無法在堆疊中擁有一個陣列)
#include <iostream>
#include <fstream>
int main() {
std::ifstream input("hello.txt", std::ios::binary);
char* buffer;
size_t len; // if u don't want to delete the buffer
if (input) {
input.seekg(0, input.end);
len = input.tellg();
input.seekg(0, input.beg);
buffer = new char[len];
input.read(buffer, len);
input.close();
std::ofstream fileOut("newhello.txt");
fileOut.write(buffer, len);
fileOut.close();
// delete[] buffer; u may delete the buffer or keep it for further use anywhere else
}
}
這應該可以解決您的問題,len如果您不想洗掉它,請記住始終擁有緩沖區的長度(此處)。
更多在這里
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/396497.html
