写入文件

文件操作 / 文本文件

const char *fileName = "file.txt";

//"w" creates the file or empties an existing one
FILE *outFile = fopen(fileName, "w");
if (outFile == nullptr) {
    perror(fileName);
    exit(EXIT_FAILURE);
}

fputs("Line 1\n", outFile);
//fprintf writes by a format, like printf
fprintf(outFile, "Line %d\n", 2);

//ftell tells how many bytes are written so far
long size = ftell(outFile);
//size is 14

//the text reaches the disk on fclose, so a full disk
//shows up only here: fclose returns 0 when all is written
bool written = fclose(outFile) == 0;
//written is true

printf("size is %ld\n", size);
printf("written is %s\n", written ? "true" : "false");
remove(fileName);