文件操作的格式:
读取内容
#include <stdio.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int num;
char type;
char errorInfile[]="/home/sen/Desktop/ITSC202/file.txt";
//error message for text file
int inputStatus;//declare loop variable
FILE *infile;//point to memory location for infile
infile = fopen("/home/sen/Desktop/ITSC202/file.txt", "r");//open infile
if(infile == NULL)//error check opening infile
{
fprintf(stderr, "Error: Cannot open infile %s\n", errorInfile);
exit(1);//unsuccessful exit
}
inputStatus = fscanf(infile, "%c %d", &type, &num);
//scan for infile values
while(inputStatus!=EOF)//scan infile line by line until end of file
{
printf("%c %d", type, num);//print infile values
inputStatus = fscanf(infile, " %c %d", &type, &num);
//scan for infile values
printf("\n");
}
fclose(infile);//close infile
return 0;
}
写入内容
FILE *fp; //定义文件指针
fp=fopen("file.txt", "w"); //打开文件并写入
for(k=0;k<=5;k++)
fprintf(fp, "%c %d\n", a[k], b[k]); //写入内容
fclose(fp); // 关闭文件