1 //testfile.cpp --- test file i/o -- copyLeft by tsaiwn@csie.nctu.edu.tw 2 #ifdef unix 3 #ifndef __unix__ 4 #define __unix__ 5 #endif 6 #endif 7 #include /* strlen, str... */ 8 #include /** fopen, printf, ... **/ 9 #include 10 #include /*** O_CREAT, O_... ***/ 11 #ifdef __unix__ 12 #include /*** S_IWRITE defined in this file ***/ 13 #else 14 #include /*** S_IWRITE defined in this file ***/ 15 #endif 16 17 #ifdef __unix__ 18 #include /* required for new version */ 19 #define O_TEXT O_RDWR 20 #else 21 #include /*** open, write, read ***/ 22 #include /**** for "system" function calls ****/ 23 #endif 24 25 #define crln printf("\n") 26 void test1(void) 27 { 28 long kk=12345678; /** printf --Ctrl_F1--> data type **/ 29 printf("in test1 .. "); 30 printf("\nkk=%d ?? %ld ??? %Ld\n",kk, kk, kk); 31 printf(" Correct kk=%ld\n================\n",kk); 32 } 33 int main(void) 34 { 35 int handle; // an integer for System calls open/read/write/close 36 FILE *in, *out; // FILE pointer for standard fxxx functions 37 int i,j; 38 char msg[] = "Hello world"; 39 printf("\nTest file I/O --- by tsaiwn@csie.nctu.edu.tw\n"); 40 printf("\n== call test1 to test printf with wrong %%format ==\n"); 41 test1(); 42 for(i=1; i <= 9; crln, i++) 43 for(j=1; printf("%5d",i*j), j<=8; j++); 44 if ((handle = open("TEST.del", O_CREAT | O_TEXT, 45 S_IWRITE | S_IREAD)) == -1) 46 { // handle should >= 0, if handle is -1 ==> open fail 47 perror("ErRor:"); return 1; 48 } 49 write(handle, "Hey, you!\n",10); // write out 10 characters 50 write(handle, msg, strlen(msg)); // the length is calculated 51 write(handle, "\n", 1); close(handle); 52 fprintf(stderr, "TEST.del created!\n"); // always on Screen 53 #ifdef __unix__ 54 system("/bin/ls -l TEST.*"); 55 #else 56 system("dir test.*"); 57 #endif 58 /****** Now try C standard Library functions fopen, ...******/ 59 if ( (in = fopen("TEST.del", "rt")) /** Read Text **/ 60 == NULL ) /*** NULL == 0 , see stdio.h ***/ 61 { 62 fprintf(stderr, "fopen -- Cannot open input file TEST.del\n"); 63 return 1; 64 } 65 while (!feof(in)) // Loop till feof(in) 66 fputc(fgetc(in), stdout); /* fputchar(??) === putchar(??) */ 67 fclose(in); 68 /****** then, type out the content of file TEST.del ******/ 69 #ifdef __unix__ 70 printf("\n%% cat -n TEST.del\n"); 71 system("cat -n TEST.del"); 72 #else 73 printf("\nC:> type test.del\n"); 74 system("type TEST.del"); 75 #endif 76 printf("\nBye bye!\n"); 77 return 0; 78 }