思路来源:https://blog.csdn.net/hongzhen91/article/details/57422897
1 写
.csv 是 excel 后缀,跳跃间隔符是 ‘,’
FILE *fp ;
fp = fopen("./test.csv","w") ; // 写
for (i=0 ; i<4 ; i++)
fprintf(fp,"%c,%d,%d\n", chy[i], data[i], d2) ;
fclose(fp);
2 读
指定位置读数,如倒序读数,从末尾向前 ( 向着开头 ) 读数!
先看 代码!
倒序读 最后一行的数据
#include<bits/stdc++.h>
#define num 20
using namespace std;
void writeExcel()
{
char chy[4]={ 'x' ,'a' ,'h','w' }, ch, t;
int data[4]={ 1 , 3 , 6 ,9 }, d1 = -1, d2 = 5;
int i ;
FILE *fp ;
fp = fopen("./test.csv","w") ; // 写
for (i=0 ; i<4 ; i++)
fprintf(fp,"%c,%d,%d\n", chy[i], data[i], 5) ;
fclose(fp);
cout << "读:" << endl;
fp = fopen("./test.csv","r") ; // 读
cout << "d1 = " << d1 << endl;
cout << "ftell(fp) = " << ftell(fp) << endl;
fseek(fp, 0L, 2); // 末尾
cout << "ftell(fp) = " << ftell(fp) << endl << endl;
fseek(fp, -3L, 1); // 向前移动 3L
cout << "ftell(fp) = " << ftell(fp) << endl;
fscanf(fp, "%d", &d1); // 5
cout << d1 << endl;
cout << "ftell(fp) = " << ftell(fp) << endl << endl;
fseek(fp, -3L, 1);
cout << "ftell(fp) = " << ftell(fp) << endl;
fscanf(fp, "%d", &d1); // 9
cout << d1 << endl;
cout << "ftell(fp) = " << ftell(fp) << endl<< endl;
fscanf(fp, "%c", &ch); // 9后面的','
cout << ch << endl;
cout << "ftell(fp) = " << ftell(fp) << endl<< endl;
fseek(fp, -4L, 1);
cout << "ftell(fp) = " << ftell(fp) << endl;
fscanf(fp, "%c", &ch); // w
cout << ch << endl;
cout << "ftell(fp) = " << ftell(fp) << endl<< endl;
fclose(fp);
}
int main()
{
writeExcel() ;
system("pause");
return 0;
}
结果分析可知
首先数据是:%c + ‘,’ + %d + ‘\n’ …
1
字节数总共 29(0 ~ 28),可见数据一共 4 行,每行字节数是 7 第 1 行,0 ~ 6 第 2 行,7 ~ 13 第 3 行,14 ~ 20 第 4 行,21 ~ 27 第 5 行,28 是文本结尾 feof(fp) |
---|
2 |
%c ‘,’ %d ‘\n’ 所占字节都是 1L |
字符 |
:– |
指针位置 |
3 |
顺序读数据 |
很容易忘了加上 & |
fscanf(fp, "%c,%d,%d\n", &ch, &d1, &d2);
逆序读
读完一个数,跳了 1L,再向前跳 3L 才是前一个数
fscanf(fp, "%d\n", &d2);
fseek(fp, -3L, 1);//从当前位置 向着开头的方向移动3L字节
fscanf(fp, "%d\n", &d2);
4
csv 文本结尾是 另开辟一行!
当从头读 或 遍历 数据时,会遍历到最后的 “空行”,具体情况要注意代码细节的不同