gpt4 book ai didi

c++ - fseek 没有读取所有数据?

转载 作者:太空宇宙 更新时间:2023-11-04 12:20:18 26 4
gpt4 key购买 nike

我正在制作一个 C++ 安装程序,我已将要提取的文件和要在程序中提取的文件的 8 字节文件大小附加到可执行文件中。我的程序因文件读取错误而退出,出了什么问题?请注意,除了我今天学到的知识外,我对 c 文件管理一无所知。我正在编写文件 test_before.tar.gz,它有 161 个字节,可执行文件有 12335 个字节长,filesize 文件有 8 个字节长,包含 0000161。有什么问题吗?如果需要,请询问更多信息。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

int main(int argc, char* argv[])
{
cout << "Opening the executable as read-only!" << endl;
FILE *exeFile; // The executable file pointer
FILE *outFile; // The file to write pointer

// Check whether a file name was supplied
if(argc < 2)
{
cout << "Please enter the file to write!" << endl;
return 1;
}

// Open the executable as read-only
if((exeFile = fopen(argv[0], "rb")) == 0)
{
cout << "Error opening the executable!" << endl;
return 1;
}

cout << "Getting the executables size!" << endl;

// Get the files size
fseek(exeFile, 0, SEEK_END);
int size = ftell(exeFile);

cout << "Reading ofset!" << endl;

// Read the ofset bytes contained in the last 7-bytes
char filesize_char[9];
fseek(exeFile, -8, SEEK_END);
fgets(filesize_char, 9, exeFile);

// Convert
int filesize = atoi(filesize_char);
int ofset = (size - filesize) - 8;

cout << "The ofset size is " << ofset << " bytes!" << endl;
cout << "The file size is " << filesize << " bytes!" << endl;

cout << "Reading the file to extract!" << endl;

// Create the variable to contain the file and goto the ofset
char* contents = new char[filesize + 1];
fseek(exeFile, ofset, SEEK_SET);

// Read the file to extract
if(fread(contents, sizeof(char), filesize + 1, exeFile) != sizeof(contents))
{
// Error has occured
if(feof(exeFile)) {
cout << "Premature end of file!" << endl;

// Delete variables so they dont "leak"
fclose(exeFile);
delete[] contents;

return 1;
} else {
cout << "File read error!" << endl;

// Delete variables so they dont "leak"
fclose(exeFile);
delete[] contents;

return 1;
}
}

cout << "Writing the file to " << argv[1] << "!" << endl;

// Write the file to extract
if((outFile = fopen(argv[1], "wb")) == 0)
{
cout << "Error opening the file to write!" << endl;

// Delete variables so they dont "leak"
fclose(exeFile);
fclose(outFile);
delete[] contents;

return 1;
}

fwrite(contents, 1, sizeof(contents), outFile);

//delete variables
fclose(exeFile);
fclose(outFile);
delete[] contents;

return 0;
}

最佳答案

您根本不需要 while 循环。毕竟,您已经分配了包含所有数据的内存。将文件指针移动到数据的开头 fseek(exeFile, ofset, SEEK_SET),然后使用 fread 整体读取它,然后使用 fwrite 将其写入 outFile

你应该用 "rb""wb" 标志打开你的 exeFileoutFile 否则你的代码仅对文本数据可靠地工作。

关于c++ - fseek 没有读取所有数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5478147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com