c++ - ios按行读取一个50M的文件,再对每行数据进行存储,请问如何降低运行内存?
伊谢尔伦
伊谢尔伦 2017-04-17 18:01:38
[iOS讨论组]

读取一个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++基础不好,惭愧)

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(5)
天蓬老师

不多说了,直接上代码:

`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];`

有疑问可以追问讨论

ringa_lee

使用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);

}

ringa_lee

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

ringa_lee

autoreleasepool 应该有帮助的

巴扎黑

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号