參考:
【2】https://mp.csdn.net/console/editor/html/105208262
————————————————————————
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
//C語言向文件存入數據
void writeFile()
{
FILE *fp;
fp = fopen("0501.txt", "w");
if (!fp)
{
printf("文件打開失敗\n");
return;
}
fprintf(fp, "%s\n", "1234hello");
fprintf(fp, "%s\n", "1234hello");
fclose(fp);
printf("數據存儲完成\n");
}
//使用C語言讀取文件
void ReadFile1()
{
FILE *fp;
fp = fopen("0501.txt", "r");
if (!fp)
{
printf("文件打開失敗\n");
return;
}
//讀取第一行:fgets
char str1[20];
fgets(str1, 10, fp);
cout << str1 << endl;
//分解第一行
char str1_1[20] = { 0 };
strncpy(str1_1, str1, 4);
cout << str1_1 << endl;
char str1_2[20] = { 0 };
strncpy(str1_2, str1+4, 5);
cout << str1_2 << endl;
//讀取第2行:fscanf
char str2[20];
fscanf(fp, "%s", str2);
cout << str2 << endl;
char str2_1[20] = { 0 };
strncpy(str2_1, str2, 4);
cout << str2_1 << endl;
char str2_2[20] = { 0 };
strncpy(str2_2, str2 + 4, 5);
cout << str2_2 << endl;
fclose(fp);
printf("數據讀取完成\n");
}
int main()
{
writeFile();//使用C語言寫文件
ReadFile1();//使用C語言讀取文件
return 0;
}