相关疑难解决方法(0)

将整个ASCII文件读入C++ std :: string

我需要将整个文件读入内存并将其放在C++中std::string.

如果我把它读成a char[],答案很简单:

std::ifstream t;
int length;
t.open("file.txt");      // open input file
t.seekg(0, std::ios::end);    // go to the end
length = t.tellg();           // report location (this is the length)
t.seekg(0, std::ios::beg);    // go back to the beginning
buffer = new char[length];    // allocate memory for a buffer of appropriate dimension
t.read(buffer, length);       // read the whole file into the buffer
t.close();                    // close file handle

// ... Do stuff with buffer here ...
Run Code Online (Sandbox Code Playgroud)

现在,我想做同样的事情,但是使用a std::string而不是a char[] …

c++ string file-io caching standard-library

559
推荐指数
5
解决办法
49万
查看次数

如何在C++中获取文件大小?

让我们为这个问题创建一个补充问题.在C++中获取文件大小的最常用方法是什么?在回答之前,确保它是可移植的(可以在Unix,Mac和Windows上执行),可靠,易于理解且没有库依赖(没有boost或qt,但是例如glib是可以的,因为它是可移植的库).

c++ filesize

123
推荐指数
5
解决办法
24万
查看次数

tellg()函数给出错误的文件大小?

我做了一个示例项目,将文件读入缓冲区.当我使用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)

c++ file ifstream

23
推荐指数
2
解决办法
3万
查看次数

C++:获取不正确的文件大小

我正在使用Linux和C++.我有一个大小为210732字节的二进制文件,但使用seekg/tellg报告的大小为210728.

我从ls-la获得以下信息,即210732字节:

-rw-rw-r-- 1 pjs pjs 210732 Feb 17 10:25 output.osr

并使用以下代码片段,我得到210728:

std::ifstream handle;
handle.open("output.osr", std::ios::binary | std::ios::in);
handle.seekg(0, std::ios::end);
std::cout << "file size:" << static_cast<unsigned int>(handle.tellg()) << std::endl;
Run Code Online (Sandbox Code Playgroud)

所以我的代码关闭了4个字节.我已使用十六进制编辑器确认文件的大小是正确的.那么为什么我没有得到正确的尺寸?

我的回答:我认为这个问题是由于文件中有多个开放的fstream引起的.至少那似乎已经为我解决了.感谢所有帮助过的人.

c++ linux

10
推荐指数
2
解决办法
4351
查看次数

如何获取文件的大小

可能重复:
使用C++文件流(fstream),如何确定文件的大小?
c程序中的文件大小

我想要检索文件的大小,为此我以这种方式实现

(void)fseek(m_fp, 0, SEEK_END); // Set the file pointer to the end of the file
pFileSize = ftell(m_fp);        // Get the file size
(void)fseek(m_fp, oldFilePos, SEEK_SET);  // Put back the file pointer at the original location
Run Code Online (Sandbox Code Playgroud)

这对于out out是不可行的,并且是获取文件大小或检查文件是否包含数据的任何其他方式

c c++ file-io

2
推荐指数
1
解决办法
330
查看次数

标签 统计

c++ ×5

file-io ×2

c ×1

caching ×1

file ×1

filesize ×1

ifstream ×1

linux ×1

standard-library ×1

string ×1