1. 程式人生 > >69.fprintf fscanf

69.fprintf fscanf

++ file fop pre with 取字符 blog system 字符串

  • fprintf
    1 //從讀文件中提取字符串到info1.user和info1.password中
    2 fscanf(pfr, "%s%s", info1.user, info1.password);

  • fscanf
    1 //格式化寫入到文件中
    2 fprintf(pfw, "%d %s %s\n", i, info1.user, info1.password);

完整代碼:

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 
 5 //創建結構體
6 typedef struct info7k7k 7 { 8 char user[50]; 9 char password[50]; 10 11 }INOF,* PINOF; 12 13 void main2x() 14 { 15 //以讀的方式打開文件 16 FILE *pfr = fopen("7k7kOK.txt", "r"); 17 //以寫的方式打開文件 18 FILE *pfw = fopen("7k7kOKwithid.txt", "w"); 19 //編號 20 int i = 0; 21 //如果沒到文件末尾 22
while (!feof(pfr)) 23 { 24 i++; 25 //創建結構體 26 INOF info1; 27 //從讀文件中提取字符串到info1.user和info1.password中 28 fscanf(pfr, "%s%s", info1.user, info1.password); 29 //格式化寫入到文件中 30 fprintf(pfw, "%d %s %s\n", i, info1.user, info1.password); 31 } 32 //
關閉文件 33 fclose(pfr); 34 fclose(pfw); 35 system("pause"); 36 } 37 38 void main3x() 39 { 40 //int num = fprintf(stdout, "helloword%s","1234"); 41 //printf("\n%d", num);//fprintf返回值就是寫入成功字符的個數 42 FILE *pf = fopen("C:\\x.txt", "r"); 43 int num = fprintf(pf, "helloword%s", "1234");//寫入失敗返回-1 44 printf("\n%d", num); 45 system("pause"); 46 } 47 48 void main() 49 { 50 //char str[128] = { 0 }; 51 //int numa; 52 //int numb; 53 //int num = fscanf(stdin, "%s%d%d",str,&numa,&numb); 54 ////返回值是掃描到幾個數據,失敗返回-1 55 //printf("\n%d", num); 56 FILE *pf = fopen("C:\\x.txt", "w"); 57 char str[128] = { 0 }; 58 int numa; 59 int numb; 60 int num = fscanf(pf, "%s%d%d",str,&numa,&numb); 61 printf("\n%d", num); 62 63 system("pause"); 64 65 }

69.fprintf fscanf