VS2017文件操作之使用fopen函数总结
fopen中mode參數 r, w, a, r+, w+, a+ 具體區別
r : 只能讀, 必須存在, 可在任意位置讀取
w : 只能寫, 可以不存在, 必會擦掉原有內容從頭寫
a : 只能寫, 可以不存在, 必不能修改原有內容, 只能在結尾追加寫, 文件指針無效
r+ : 可讀可寫, 必須存在, 可在任意位置讀寫, 讀與寫共用同一個指針
w+ : 可讀可寫, 可以不存在, 必會擦掉原有內容從頭寫
a+ : 可讀可寫, 可以不存在, 必不能修改原有內容, 只能在結尾追加寫, 文件指針只對讀有效 (寫操作會將文件指針移動到文件尾)
?
r+ 和 w+ 的區別:
?r+ 是可以直接寫在文件上,讀取和寫入的光標都在文件開頭。
?w+ ,如果文件已經存在,將建立一個新文件覆蓋原文件(很缺德啊……),并且支持讀取。
?
a+ 和 r+:
?a+只能在文件最后補充,光標在結尾。
?r+可以覆蓋前面的內容,光標在開頭
?
VS2017的例子:
#include "pch.h"
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <stdarg.h>
#include <time.h>?
int write_log (FILE* pFile, const char *format, ...)?
{?? ?
?? ?va_list arg;?? ?
?? ?int done; ?? ?
?? ?va_start (arg, format);?? ?
?? ?//done = vfprintf (stdout, format, arg); ?? ?
?? ?time_t time_log = time(NULL);?? ?
?? ?struct tm* tm_log = localtime(&time_log);?? ?
?? ?fprintf(pFile, "%04d-%02d-%02d %02d:%02d:%02d ", tm_log->tm_year + 1900, tm_log->tm_mon + 1, tm_log->tm_mday, tm_log->tm_hour, tm_log->tm_min, tm_log->tm_sec); ?? ?
?? ?done = vfprintf (pFile, format, arg);?? ?
?? ?va_end (arg); ?? ?
?? ?fflush(pFile);?? ?
?? ?return done;
}?
int main()?
{?? ?
?? ?FILE* pFile = fopen("123.txt", "a+");?? ?
?? ?write_log(pFile, "%s %d %f\n", "is running", 10, 66.66);?? ?
?? ?fclose(pFile); ?? ?
?? ?return 0;
}
?
總結
以上是生活随笔為你收集整理的VS2017文件操作之使用fopen函数总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VC++之自定义消息
- 下一篇: VC++ 使用预编译头