C++向文件写日志,当文件大小超过10k时,新建一个继续写

C++向文件写日志,当文件大小超过10k时,新建一个继续写,第1张

#include<iostream>

#include<fstream>

#include<cstring>

#include<ioh>

using namespace std;

long int getLen(ifstream &fs);

void main()

{

string fpath="tmp1log";

string fpath1="tmp2log";

ofstream os("tmp1log",ios::app);

ifstream is("tmp1log");

char  logContent="this is a log file";

long int restBytes = 101024-getLen(is); //剩余字节数

while(restBytes > (int)strlen(logContent))//这里简化了大小的计算

{

os<<logContent<<endl;

restBytes-=1+strlen(logContent);

}

osflush();

osclose();

isclose();

//然后可以写入到第二个文件

osopen("tmp2log",ios::app);

isopen("tmp2log");

restBytes = 101024-getLen(is);

while(restBytes > (int) strlen(logContent)){

os<<logContent<<endl;

restBytes-=1+strlen(logContent);

}

osflush();

osclose();

isclose();

 

}

//获取文件的字节数

long int getLen(ifstream &fs)

{

fsseekg(0,ios::end);

long int len =fstellg();

return len;

}

这里仅仅是做个演示,你可以将其写成循环的形式

数组不知道长度?

数据不知道大小?

没关系!

STL的动态数组vector可以帮到你!

只需添加库vector!

只要你需要

它随时可以为你扩充数组大小(内存空间)!

并且是自动的!

如果数据较大,你也可以使用它自带的函数来初始化它的最初大小!(当然它内存不够时还会自动扩充)

避免了因之后的扩充造成的时间复杂度提高!

它的具体用法比我知道的多的人网上有很多,请百度:C++vector用法

以上就是关于C++向文件写日志,当文件大小超过10k时,新建一个继续写全部的内容,包括:C++向文件写日志,当文件大小超过10k时,新建一个继续写、c++中读取一个不知道长度的文件怎么读取。 比如一个新闻稿,要用数组读取,但是不知道它的具体长度怎么办、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/9542860.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-29
下一篇 2023-04-29

发表评论

登录后才能评论

评论列表(0条)

保存