//testfile.cpp --- test file i/o -- copyLeft by tsaiwn@csie.nctu.edu.tw #ifdef unix #ifndef __unix__ #define __unix__ #endif #endif #include /* strlen, str... */ #include /** fopen, printf, ... **/ #include #include /*** O_CREAT, O_... ***/ #ifdef __unix__ #include /*** S_IWRITE defined in this file ***/ #else #include /*** S_IWRITE defined in this file ***/ #endif #ifdef __unix__ #include /* required for new version */ #define O_TEXT O_RDWR #else #include /*** open, write, read ***/ #include /**** for "system" function calls ****/ #endif #define crln printf("\n") void test1(void) { long kk=12345678; /** printf --Ctrl_F1--> data type **/ printf("in test1 .. "); printf("\nkk=%d ?? %ld ??? %Ld\n",kk, kk, kk); printf(" Correct kk=%ld\n================\n",kk); } int main(void) { int handle; // an integer for System calls open/read/write/close FILE *in, *out; // FILE pointer for standard fxxx functions int i,j; char msg[] = "Hello world"; printf("\nTest file I/O --- by tsaiwn@csie.nctu.edu.tw\n"); printf("\n== call test1 to test printf with wrong %%format ==\n"); test1(); for(i=1; i <= 9; crln, i++) for(j=1; printf("%5d",i*j), j<=8; j++); if ((handle = open("TEST.del", O_CREAT | O_TEXT, S_IWRITE | S_IREAD)) == -1) { // handle should >= 0, if handle is -1 ==> open fail perror("ErRor:"); return 1; } write(handle, "Hey, you!\n",10); // write out 10 characters write(handle, msg, strlen(msg)); // the length is calculated write(handle, "\n", 1); close(handle); fprintf(stderr, "TEST.del created!\n"); // always on Screen #ifdef __unix__ system("/bin/ls -l TEST.*"); #else system("dir test.*"); #endif /****** Now try C standard Library functions fopen, ...******/ if ( (in = fopen("TEST.del", "rt")) /** Read Text **/ == NULL ) /*** NULL == 0 , see stdio.h ***/ { fprintf(stderr, "fopen -- Cannot open input file TEST.del\n"); return 1; } while (!feof(in)) // Loop till feof(in) fputc(fgetc(in), stdout); /* fputchar(??) === putchar(??) */ fclose(in); /****** then, type out the content of file TEST.del ******/ #ifdef __unix__ printf("\n%% cat -n TEST.del\n"); system("cat -n TEST.del"); #else printf("\nC:> type test.del\n"); system("type TEST.del"); #endif printf("\nBye bye!\n"); return 0; }