برای فهم بهتر این مثالها میتونید یک برنامه ساده براش بنویسید.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
Run
$ gcc -Wall run.c -o run; ./run
*/
void skip_whitespace(FILE *stream) {
int c;
do {
/* No need to check for EOF because it is not
isspace, and ungetc ignores EOF. */
c = getc(stream);
printf("read: %c, %d\n", c, c);
//} while (!isspace(c));
} while (isspace(c));
int b = ungetc(c, stream);
printf("put: %c, %d\n", b, b);
}
int main(void) {
// printf("Hell world!\n");
// char str[] = " simple text";
// printf("%s\n", str);
FILE *fptr = fopen("test.txt", "r");
char string[100] = "";
fgets(string, 100, fptr);
// print the file content
printf("stream:\n%slen: %ld\n", string, strlen(string));
// move pointer to start position
rewind(fptr);
skip_whitespace(fptr);
char string2[100] = "";
fgets(string2, 100, fptr);
printf("stream:\n%slen: %ld\n", string2, strlen(string2));
// close the file
fclose(fptr);
return 0;
}
این یک نمونه از اجرای برنامه روی فایلی با محتویات متن هست. همانطور که میبینید کاراکترهای فاصله را که در ابتدا قرار دارند از جریان داده fptr حذف کرده.
$ gcc -Wall run.c -o run; ./run
stream:
simple
len: 9
read: , 32
read: , 32
read: s, 115
put: s, 115
stream:
simple
len: 7