首页 > ios按行读取一个50M的文件,再对每行数据进行存储,请问如何降低运行内存?

ios按行读取一个50M的文件,再对每行数据进行存储,请问如何降低运行内存?

读取一个50M的文件,运行内存最高达到了330M左右,示例代码如下:

float *squareVertexData;
    int faceNum;

//文件路径
    const char* destDir = [fileName UTF8String];//将NSString转为char *字符串
   
    ifstream inSTL;
    string fp  = destDir;
    destDir = nil;
    inSTL.open(fp);
    //定义一个vector容器,用于存储float数组
    vector<float>vec;
    
    while(!inSTL.eof())
    {

        string line;
        getline(inSTL, line);
        //将处理后需要的东西存入Vector容器
        vec.push_back(line.substr(1, 2));//这段代码为举例
     }
     

上述代码运行过程中运行内存会达到330M左右,请问怎么解决?
有朋友说分段去读取文件,比如每3m读取一次存起来,再读下3M,思路明白,但不知道怎么操作(c++基础不好,惭愧)


数据读出来,然后存下来,即便一段段读取,如果数据一直在内存中,需要全部读取后才能利用,那还是要消耗内存的。
关键在于如果根据不同应用场景,根据不同算法或者需求,将每次分段读取的数据利用起来,然后抛弃,继续读下一块。


string line; //移到while外面应该会好很多


autoreleasepool 应该有帮助的


不多说了,直接上代码:

`NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSInteger count = 0;
NSInteger  dataLength = 1024*1024;
NSData *data = [fileHandle readDataOfLength:dataLength];

while (YES) {
    [fileHandle seekToFileOffset:count*dataLength];
    data = [fileHandle readDataOfLength:dataLength];
    
    if (!data||[data length]<=0) {
        break;
    }
    
    //do things with data,for example:
    [self uploadPartialData:data];
    count++;
}

[fileHandle closeFile];`

有疑问可以追问讨论


使用fstream ,可以用同一个文件句柄进行读写操作。
int readsize=30;
char readBuf[readsize];
fstream wfile("test.txt");
while(!wfile.eof())
{

memset(readBuf, 0, sizeof(readBuf) / sizeof(char));
//使用get按字节读取
rfile.get(readBuf, readSize, EOF);

}

【热门文章】
【热门文章】