一个操作模板
使用fscanf, fprintf等
看一个代码
//input.txt
3 2
0 1 1
1 2 2
A B C
#include<stdio.h>
#include<stdlib.h>
/*这里截取部分代码*/
int main()
{
MGraph Graph;
Edge E;
Vertex V;
int Nv, i;
//file operation
FILE *fp;
fp = fopen("input.txt", "r+");//“r+” 以可读写方式打开文件,该文件必须存在,d:\\1.txt表示d盘根目录下的1.txt文件
if (fp == NULL)
{
printf("Cannot open the file!\n");
exit(0);
}
fscanf(fp, "%d ", &Nv); /* 读入顶点个数 */
Graph = CreateGraph(Nv); /* 初始化有Nv个顶点但没有边的图 */
fscanf(fp, "%d\n", &(Graph->Ne)); /* 读入边数 */
if (Graph->Ne != 0) { /* 如果有边 */
E = (Edge)malloc(sizeof(struct ENode)); /* 建立边结点 */
/* 读入边,格式为"起点 终点 权重",插入邻接矩阵 */
for (i = 0; i<Graph->Ne; i++) {
fscanf(fp, "%d %d %d", &E->V1, &E->V2, &E->Weight);
/* 注意:如果权重不是整型,Weight的读入格式要改 */
InsertEdge(Graph, E);
}
}
/* 如果顶点有数据的话,读入数据 */
for (V = 0; V<Graph->Nv; V++)
fscanf(fp, " %c", &(Graph->Data[V]));
fclose(fp);//要记得关闭文件
return 0;
}
可以看到,以下操作是一般流程
FILE *fp;
fp=fopen("fileName","r+");
if(fp==NULL){
printf("Can't Open!");
exit(0);
}
int a;
fsanf(fp, "%d", &a);
...
fprintf("%d",a);
fclose(fp);
把文件内容变成stdin
freopen("input.txt", "r", stdin);
//然后后面就可以认为文件内容都变成屏幕输入了。
scanf.....
打开其他目录下的文件
一般文件放在c程序目录下,就可以直接读,但是对于其它目录的文件,不能直接复制目录,需要把"“改成”\",因为\是转义字符。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include <direct.h>
int main()
{
FILE *fp=fopen("C:\\Users\\胡帆\\Desktop\\math\\1.txt", "r+");
//获得目录当前文件
printf("current working directory: %s\n", getcwd(NULL, NULL));
fprintf(fp, "%s\n", "Hello World!\0"); //文件操作
fclose(fp);
}
feof判断文件是否结束
feof(fp)==0, not end;
feof(fp)==1, ended.
文件的定位
rewind
rewind(fp) :使fp重新指向开头。
fseek
fseek(fp, 位移量, 起始点);
起始点:0代表“文件开始”,1代表“当前位置”, 2代表“文件末尾”。
fseek(fp,-50L,1); //将fp后退移动,离当前位置50字节处。