可能重复:
如何确定C中文件的大小?
如何找出用C语言编写的应用程序打开的文件大小?我想知道大小,因为我想把加载文件的内容放入一个我分配的字符串中malloc().只是写作malloc(10000*sizeof(char));是恕我直言,一个坏主意.
对于这个问题,这可能不是一个非常合适的论坛,但是让我试一试,冒着被搬走的风险.
C++标准库有几个参考,包括非常有价值的ISO标准,MSDN,IBM,cppreference和cplusplus.就个人而言,在编写C++时,我需要一个具有快速随机访问,短加载时间和使用示例的引用,并且我一直在发现cplusplus.com非常有用.但是,我一直在SO上听到关于该网站的负面看法,所以我想具体说明:
cplusplus.com提供的错误,误解或错误建议有哪些?使用它来做出编码决策有哪些风险?
让我补充一点:我希望能够通过标准的准确报价在这里回答问题,因此我想发布可立即使用的链接,而cplusplus.com将是我选择的网站,如果不是这个问题.
我确定我在手册中错过了这个,但是如何使用标题中的C++ istream类来确定文件的大小(以字节为单位)fstream?
我做了一个示例项目,将文件读入缓冲区.当我使用tellg()函数时,它给我一个比读取函数实际读取的值更大的值.我认为有一个错误.
这是我的代码:
编辑:
void read_file (const char* name, int *size , char*& buffer)
{
ifstream file;
file.open(name,ios::in|ios::binary);
*size = 0;
if (file.is_open())
{
// get length of file
file.seekg(0,std::ios_base::end);
int length = *size = file.tellg();
file.seekg(0,std::ios_base::beg);
// allocate buffer in size of file
buffer = new char[length];
// read
file.read(buffer,length);
cout << file.gcount() << endl;
}
file.close();
}
Run Code Online (Sandbox Code Playgroud)
主要:
void main()
{
int size = 0;
char* buffer = NULL;
read_file("File.txt",&size,buffer);
for (int i = 0; i < size; i++) …Run Code Online (Sandbox Code Playgroud) 我正在编写单元测试,需要将结果文件与黄金文件进行比较.最简单的方法是什么?
到目前为止我(对于Linux环境):
int result = system("diff file1 file2");
Run Code Online (Sandbox Code Playgroud)
如果他们是不同的 result != 0
我试图将整个file.txt读入一个char数组.但有一些问题,建议请=]
ifstream infile;
infile.open("file.txt");
char getdata[10000]
while (!infile.eof()){
infile.getline(getdata,sizeof(infile));
// if i cout here it looks fine
//cout << getdata << endl;
}
//but this outputs the last half of the file + trash
for (int i=0; i<10000; i++){
cout << getdata[i]
}
Run Code Online (Sandbox Code Playgroud) 我有一个类型的文件流ofstream.构造函数以追加模式打开文件,所有消息总是写在文件末尾.
我需要写入一些固定大小的输出文件,例如1Mb,然后我需要关闭,重命名和压缩它,然后打开一个同名的新文件.
这需要在达到特定大小的文件时完成.
我尝试使用tellg()但是在网上阅读了东西(和这个)后,我明白这不是正确的方法.
由于我是C++的新手,我正在尝试找出最优化和正确的方法来获得准确的文件当前大小ofstream?
class Logger {
std::ofstream outputFile;
int curr_size;
Logger (const std::string logfile) : outputFile(FILENAME,
std::ios::app)
{
curr_size = 0;
}
};
Run Code Online (Sandbox Code Playgroud)
在程序的某个地方,我正在写入数据:
// ??? Determine the size of current file ???
if (curr_size >= MAX_FILE_SIZE) {
outputFile.close();
//Code to rename and compress file
// ...
outputFile.open(FILENAME, std::ios::app);
curr_size = 0;
}
outputFile << message << std::endl;
outputFile.flush();
Run Code Online (Sandbox Code Playgroud)