C-文件操作相关例题
文件操作相关例题
1
从文件"coordinate.txt"中读取X, Y数据(共10组), 计算Z = X + Y, 并将结果写入"result.txt"中.
x y
100.671 100.888
98.793 98.853
100.717 98.931
101.630 99.191
100.489 97.056
101.035 101.438
100.727 100.325
99.697 99.245
100.294 101.370
99.213 98.288
#include <stdio.h>
int main()
{
char header1, header2, header3 = 'z';
float x[10], y[10], z[10];
FILE *fp = fopen("coordinate.txt", "r");
if(fp == NULL)
{
printf("ERROR");
}
else
{
fscanf(fp, "%c %c", &header1, &header2);
for (int i = 0; i < 10; ++i)
{
fscanf(fp, "%f %f", &x[i], &y[i]);
z[i] = x[i] + y[i];
}
fclose(fp);
}
FILE *fp2 = fopen("result.txt", "w");
if(fp2 == NULL)
{
printf("ERROR");
}
else
{
fprintf(fp2, "%c %c %c\n", header1, header2, header3);
for (int i = 0; i < 10; ++i)
{
fprintf(fp2, "%f %f %f\n", x[i], y[i], z[i]);
}
fclose(fp2);
}
return 0;
}
2
将一个主对角线上元素从1增加到5, 其余元素为0的矩阵写入到文件"matrix.txt"中.
#include <stdio.h>
int main()
{
FILE *fp = fopen("matrix.txt", "w");
int value = 1;
if(fp == NULL)
printf("ERROR");
else
{
for (int i = 1; i < 6; ++i)
{
for (int j = 1; j < 6; ++j)
{
if(i == j)
fputc(value+48, fp);
else
fputc('0', fp);
}
value++;
fputc('\n', fp);
}
fclose(fp);
}
return 0;
}
3
下面是一个几何数据文件的实例 (geodata.txt), 包含线 (LINE), 矩形 (RECT) 和圆 (CIRCLE) 三种图形.
LINE #线
0 0 10 10 #x1 y1 x2 y2
RECT #矩形
10 10 20 20 #x1 y1 width height
CIRCLE #圆
20 20 40 #x1 y1 r
END #文件中无注释
- 根据不同的几何数据类型定义不同的数据结构, 存储这些数据
- 计算线的长度, 矩形和圆的面积
- 把数据和结果写入"newdata.txt"文件中
#include <stdio.h>
#include <math.h>
#include <string.h>
typedef struct
{
int x, y;
}POINT;
typedef struct
{
POINT p1, p2;
float length;
}LINE;
typedef struct
{
POINT p;
int width, height;
float area;
}RECT;
typedef struct
{
POINT p;
int r;
float area;
}CIRCLE;
int judge(char *str)
{
char *c1 = "LINE";
char *c2 = "RECT";
char *c3 = "CIRCLE";
if(!strcmp(c1, str))
return 1;
if(!strcmp(c2, str))
return 2;
if(!strcmp(c3, str))
return 3;
}
int main()
{
LINE line;
RECT rect;
CIRCLE circle;
char *header = NULL;
FILE *fp = fopen("geodata.txt", "r");
if(fp == NULL)
printf("ERROR");
else
{
fscanf(fp, "%s", header);
while(strcmp(header, "END") != 0)
{
int k = judge(header);
switch(k)
{
case 1:
fscanf(fp, "%d %d %d %d", &line.p1.x, &line.p1.y, &line.p2.x, &line.p2.y);
line.length = (float)sqrt((line.p1.x-line.p2.x)*(line.p1.x-line.p2.x)+(line.p1.y-line.p2.y)*(line.p1.y-line.p2.y));
break;
case 2:
fscanf(fp, "%d %d %d %d", &rect.p.x, &rect.p.y, &rect.width, &rect.height);
rect.area = (float)(rect.width * rect.height);
break;
case 3:
fscanf(fp, "%d %d %d", &circle.p.x, &circle.p.y, &circle.r);
circle.area = M_PI * pow(circle.r, 2);
break;
}
fscanf(fp, "%s", header);
}
fclose(fp);
}
fp = fopen("newdata.txt", "w");
if(fp == NULL)
printf("ERROR");
else
{
fprintf(fp, "%s\n%d %d %d %d %f\n", "LINE", line.p1.x, line.p1.y, line.p2.x, line.p2.y, line.length);
fprintf(fp, "%s\n%d %d %d %d %f\n", "RECT", rect.p.x, rect.p.y, rect.width, rect.height, rect.area);
fprintf(fp, "%s\n%d %d %d %f\n", "CIRCLE", circle.p.x, circle.p.y, circle.r, circle.area);
fclose(fp);
}
return 0;
}