Delete logs after N Days

Hi. I have a website. I'm getting logs via syslog to my website.
I want to write a c++ code for, delete the logs after 30 days.
How can i do it?
I have no idea about it.
Thank you for your helps and ideas.
logrotate not good enough?
@kbw, logrotate presumes the OS is *nix. No such handy sysadmin feature that I know of with Windows.

Creating such a nifty tool could be a wonderful learning experience now that C++ has a filesystem library in the standard.
Thank you for all answers.
Is there any idea about the code?
Are you able to go to the directory and get a list of the files?

Do the filenames already encode the date (say log-yyyymmdd.txt) or are they something cryptic (log1.txt, log2.txt).

Iterate the folder containing the logs
https://en.cppreference.com/w/cpp/filesystem/directory_iterator

for each file:

Get the file last write time
https://en.cppreference.com/w/cpp/filesystem/last_write_time

If the file is older than required then remove the file
https://en.cppreference.com/w/cpp/filesystem/remove
Thank you. I will try it immediately. But i cannot include file system. Is it still used?
You need a reasonably up to date compiler.
https://en.cppreference.com/w/cpp/filesystem
filesystem was added in C++17.
you can do this with a batch file, but it may be as much or more work than the c++.

https://stackoverflow.com/questions/51054/batch-file-to-delete-files-older-than-n-days
forfiles -p "C:\what\ever" -s -m *.* -d <number of days> -c "cmd /c del @path"

or..
https://serverfault.com/questions/361621/using-logrotate-on-win7-with-cygwin
Last edited on
Hi everyone. Im thankful for all your answers.
I want to ask something too.
What if i want to use linux commands in my program.
I want to do it this operation with linux commands but i want to use c++ also.
You're just moving files. I'm not sure asio has a place here.
you can use the dreaded system() function to invoke the command line. It is a risk, but very powerful for your own personal programs on your own personal computer. If you are releasing a tool for others, you can research safer methods. The risk is simply that a rogue executable file can be placed over the real program you invoke to do harm, letting your program call it with your creds (its easier to get a file on a box than to run it, so tricking the user into running it is sometimes a hacker strategy).

the more popular and widespread your tool is, the more of an issue that is. I have a dozen c++ programs that are glorified batch files doing the same thing. But I don't let them out to the public, either... it is a powerful technique, scripts and batch files have limitations that you can get around in c++, whether that avoids a large unwieldy and weird hack to work around a limit or enabling something you can't do at all.
Last edited on
Topic archived. No new replies allowed.