https://sourceware.org/glibc/manual/2.40/html_node/How-Unread.html
#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;
}
$ 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
man ascii
man fgetc
فقط من نفهمیدم چطوری ungetc بدون ویرایش پرونده یک حرفی که درون پرونده نیستو میتونه به جای یک حرف دیگه که درون پرونده هست بذاره تا اون حرف اصلیه خوانده نشه. اون حرف جدیده کجا ذخیره میشه؟
حله
تو همون بافر ذخیره میشه. بعد از rewine یا fseek پاک میشه.
حالا چون ارجاع متغیر fptr به درون تابع از نوع reference بوده(البته احتمالا این اصطلاح در اینجا دقیق نیست) و تغییراتی که داخل تابع روی fptr انجام دادیم حفظ خواهد شد.
#include <stdio.h>
void foo(int *x) {
// *x = 12;
//*x = (*x)++;// UB
*x = (*x) + 1;
}
int main(void) {
printf("pointers in C\n");
int a = 10;
int c = 42;
int *b;
b = &c;
printf("a before: %d \n", a);
printf("b before: %d \n", *b);
foo(&a);
foo(b);
printf("a after: %d \n", a);
printf("b after: %d \n", *b);
return 0;
}
$ gcc -Wall point.c -o point; ./point
pointers in C
a before: 10
b before: 42
a after: 11
b after: 43
What are pointers really good for, anyway?
(simulated) by-reference function parameters (see question 4.8 and 20.1)
Remember that arguments in C are passed by value.
https://c-faq.com/ptrs/goodfor.html