#include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { FILE *fp = NULL; char name[12] = "tom"; int age = 12; int ret = 0; char readName[12]; int readAge; // scanf("%s",name); //不能手动输入字符串,会导致读取不出来字符 // scanf("%d",&age); #if 0 //字符串写入文件 fp = fopen("./file","w"); if(!fp) { printf("fopen error!\n"); return -1; } //将字符串写入fp指向文件 ret = fprintf(fp,"%s : %d\n",name,age); if(ret<0) //fprintf返回写入字符数,发生错误,返回一个负值 { printf("fprintf error!\n"); return -1; } #else fp = fopen("./file","r"); if(!fp) { printf("fopen error!\n"); return -1; } //读取fp的内容,写入name,age内 ret = fscanf(fp,"%s : %d",readName,&readAge); if(ret<0) //fprintf返回写入字符数,发生错误,返回一个负值 { printf("scanf error!\n"); return -1; } printf("fscanf: name=%s,age=%d\n",readName,readAge); #endif free(fp); return 0; }
时间: 2024-11-02 15:43:35