/* * formatted_io.c * Stephanie Taylor * * Set of functions demonstrating formatted text-IO in C * */ #include #include // There are 3 FILE*'s that are included in the library // stdin: scanf reads from Terminal // stdout: printf writes to Terminal // stderr: printf writes to Terminal with emphasis (right away and sometimes with additional formatting) void test0a() { // printf( "Hi, write something: " ); fprintf( stdout, "Hi, write something: " ); // equivalent to line above // fprintf( stdout, "Hi, write something: \n" ); // if \n is there, then this is flushed out before the error message fprintf( stderr, "error, though" ); // without the \n in in the printf to stdout, the message to stderr appears first } // We use a format string to indicate what we want to read in. // The return value indicates how many format patterns were // matched. In this case, we are expecting up to 1 to be matched (%d) void test0b() { printf( "write something: " ); int readMe; int succ = scanf( "%d", &readMe ); if (succ) { printf( "Successfully read %d\n", readMe ); } else { printf( "Failed: success=%d\n", succ ); } } // how tell if end of format // we can't just put two ints back to back void test0c() { int a, b; float c; int succ; // succ = scanf( "%d%d", &a, &b ); // printf( "a=%d b=%d succ=%d\n", a, b, succ ); // printf( "hi: " ); succ = scanf( "(%d,%d)", &a, &b ); printf( "a=%d b=%d succ=%d\n", a, b, succ ); } // test fscanf to see if it automatically // does the splitting. It does. // We use the format string as a pattern-matcher // We look for a string, repeatedly. void test1a() { FILE *fp = fopen( "test.txt", "r" ); if (fp == NULL) return; //char word[100]; // strings longer than 100 will cause an error. char word[9]; // strings longer than 9 will cause an error. while (1) { int c = fscanf( fp, "%s", word); if (c == EOF) break; printf( "%d %s\n", c, word ); } } // Match more than one pattern. // We use the format string as a pattern-matcher // We look for a string followed by a space followed by an integer // If it matches both the string and num, fscanf returns 2 and puts the string in word // and the integer in my_int. // If it matches only one, it returns 1 and puts what it found in the appropriate variable. void test1b() { FILE *fp = fopen( "test.txt", "r" ); if (fp == NULL) return; char word[100]; long int my_int = 9; while (1) { int c = fscanf( fp, "%s %ld", word, &my_int ); if (c == EOF) break; printf( "%d %s %ld\n", c, word, my_int ); } } // printf is the same as fprintf to stdout, which is a FILE* that // is special. void test2() { fprintf( stdout, "Hello, world\n" ); } int main(int argc, char* argv[]) { // test0c(); // test1a(); test1b(); // test2(); return 0; }