无法将整个文本文件复制到字符数组

Cant copy the whole text file to char array

本文关键字:复制 字符 数组 文件 文本      更新时间:2023-10-16

我正在尝试使用 fstream 将整个文本文件复制到 char 数组中,但即使增加数组的大小,它也会将文本文件读取到相同的限制.我很想将其保存在 char 数组中,如果它不是动态的???任何解决方案都会很好,请

......
// smallGrams.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include<iostream>
using namespace std;
#include<string>
#include<fstream>
void readInput(const char* Path);
void removePunctucationMarks();
void removeSpacing();
void insertDots();
char * getText();
void generateUnigrams();
void generateBigrams();
void generateTrigrams();
double validateSentance(string str);
string sentenceCreation(int position);
int main()
{
char *path="alice.txt";
readInput(path);
return 0;
}
void readInput(const char* Path)
{
ifstream infile;

infile.open(Path);
if(!infile.fail())
cout<<"File opened successfully"<<endl;
else
cout<<"File failed to open"<<endl;
int arrSize=100000000;
char *arr=new char[arrSize];
int i=0;
while(!infile.eof()&&i<arrSize)
{
infile.get(arr[i]);
i++;
}
arr[i-1]='';
for(short i=0;i<arrSize&&arr[i]!='';i++)
{
cout<<arr[i];
}


}

这是一个有效的 C 样式解决方案。它检查文件大小,然后为数组分配必要的内存,并在一次调用中读取文件的所有内容。fread(( 调用返回您请求的字节数或发生错误(检查 fread(( 引用(

# include <cstring>
# include <cstdlib>
# include <cstdio>
int main(int argc, char *argv[]) {
char *data;
int data_len;
FILE *fd;
fd = fopen ("file.txt", "r");
if (fd == NULL) {
// error
return -1;
}
fseek (fd , 0 , SEEK_END);
data_len = ftell (fd);
rewind (fd);
data = (char *) malloc ((data_len + 1) * sizeof (char));
memset (data, data_len + 1, NULL);
if (fread (data, sizeof (char), data_len, fd) != data_len) {
// error
return -1;
}
printf ("%sn", data);
fclose (fd);
free (data);
return 0;
}

这里有一个简单的加倍方法...

#include<iostream>
#include<string>
#include<fstream>
#include <cstdint>
#include <cstring>
using namespace std;
void readInput(const char* Path)
{
ifstream infile;

infile.open(Path);
if(!infile.fail())
cout<<"File opened successfully"<<endl;
else{
cout<<"File failed to open"<<endl;
return;
}
int capacity=1000;
char *arr=new char[capacity];
char *temp;
int i=0;
while(infile >> arr[i])
{
i++;
if ( i >= capacity ) {
temp = new char[capacity*2];
std::memcpy(temp , arr, capacity);
delete [] arr;
arr = temp;
capacity *=2;
}
}
}
int main()
{
char *path="alice.txt";
readInput(path);
return 0;
}

当您使用 for 循环读取和显示数组内容而不是从文件中读取数据时,可能会出现此错误。 使用 int 而不是 short in for 循环,因为 short 只能增加到 32768。