Qt write to end of file

I need to write text at the end of a txt file. But I can only rewrite the whole file. How to add text to the end of a file?

Thank.

+4
source share
3 answers

Are you sure you are opening the file in add mode? QIODevice::Append

+16
source

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
    FILE *fp;
    size_t count;
    const char *str = "hello\n";
fp = fopen("yourFile.txt", "a");
if(fp == NULL) {
    perror("failed to open yourFile.txt");
    return EXIT_FAILURE;
}
count = fwrite(str, 1, strlen(str), fp);
printf("Wrote %u bytes. fclose(fp) %s.\n", count, fclose(fp) == 0 ? "succeeded" : "failed");return EXIT_SUCCESS;}

code> Just use the extra flag "a"!

+1
source

I did this after reading @Let_Me_Be's answer

QString log;
for(int i=0;i<argc;i++){
    log+= argv[i];
    log+="\n";
}

QFile logFile("log.ini");
if(logFile.open(QIODevice::Append|QIODevice::Text)){
    QTextStream outLog(&logFile);
    outLog<<log;
}
logFile.close();
0
source

Source: https://habr.com/ru/post/1774316/


All Articles