1) Line-I/O via fgets and fputs
小试牛刀
源文件 main.c
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 #define BUFFER_SIZE 1024 6 char *lineBuffer = NULL; 7 8 void buildLineBuffer() { 9 if (lineBuffer == NULL) { 10 lineBuffer = (char *)malloc(BUFFER_SIZE); 11 } 12 } 13 14 void dropLineBuffer() { 15 if (lineBuffer != NULL) { 16 free(lineBuffer); 17 } 18 } 19 20 void checkRightAfterFopen(FILE *fp) { 21 if (fp == NULL) { 22 fputs("Failed to open file. ", stderr); 23 exit(1); 24 } 25 } 26 27 int writeContents2File(const char *contents, const char *fileName) { 28 FILE *fp = fopen(fileName, "w"); 29 checkRightAfterFopen(fp); 30 fputs(contents, fp); 31 fclose(fp); 32 33 return 0; 34 } 35 36 char *readLineFromFile(const char *fileName) { 37 FILE *fp = fopen(fileName, "r"); 38 checkRightAfterFopen(fp); 39 buildLineBuffer(); 40 fgets(lineBuffer, BUFFER_SIZE, fp); 41 fclose(fp); 42 return lineBuffer; 43 } 44 45 void showAllContentsInFile(const char *fileName) { 46 FILE *fp = fopen(fileName, "r"); 47 checkRightAfterFopen(fp); 48 buildLineBuffer(); 49 while (fgets(lineBuffer, BUFFER_SIZE, fp) != NULL) { 50 printf(lineBuffer); 51 } 52 fclose(fp); 53 } 54 55 int appendContentsFromConsole2File(const char *fileName) { 56 FILE *fp = fopen(fileName, "a"); 57 checkRightAfterFopen(fp); 58 buildLineBuffer(); 59 while (fgets(lineBuffer, BUFFER_SIZE, stdin) != NULL && fputs(lineBuffer, fp) != EOF); 60 fclose(fp); 61 62 return 0; 63 } 64 65 /* 66 **由目录名和文件名取得文件的全限定名 67 **--------------------------------- 68 **建议设定用户环境变量"C_DEV_HOME"的值为该目录的父目录全限定名 69 **若当前系统环境中尚未设置该环境变量, 70 **则给出提醒并默认采用当前目录作为该目录的父目录全限定名 71 */ 72 char *getFullyQualifedFileName(const char *dirName, const char *fileName) { 73 /*访问用户环境变量以取得根目录的全限定名*/ 74 char *homedir = getenv("C_DEV_HOME"); 75 if (homedir == NULL) { 76 printf("Info: User/System Environment Varable "C_DEV_HOME" has NOT been set yet! "); 77 homedir = "."; 78 } 79 80 /*创建缓存区,用于存放文件的全限定名*/ 81 char *fullyQualifedFileNameBuffer = (char *)malloc(strlen(homedir) + strlen(dirName) + strlen(fileName) + 3); 82 *fullyQualifedFileNameBuffer = '