我做了一个示例项目,将文件读入缓冲区。当我使用tellg()函数时,它给我的值大于实际从文件中读取的read函数的值。我认为有一个错误。这是我的代码:编辑: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();}主要:void main(){  int size = 0;  char* buffer = NULL;  read_file("File.txt",&size,buffer);  for (int i = 0; i < size; i++)    cout << buffer[i];  cout << endl; }
                    
                    
                3 回答
                            饮歌长啸
                            
                                
                            
                        
                        
                                                
                    TA贡献1951条经验 获得超3个赞
void read_file (int *size, char* name,char* buffer)
*buffer = new char[length];
这些行的确看起来像个错误:创建一个char数组并将其保存到buffer [0] char。然后,您读取要缓冲的文件,该文件仍未初始化。
您需要buffer通过指针传递:
void read_file (int *size, char* name,char** buffer)
*buffer = new char[length];
或通过引用(这是c ++的方式,并且不太容易出错):
void read_file (int *size, char* name,char*& buffer)
buffer = new char[length];
...
- 3 回答
 - 0 关注
 - 645 浏览
 
添加回答
举报
0/150
	提交
		取消
	