io操作就是简单的从程序移进或移出字节的事情,这种字节流便称为流
2、流的两种类型,文本流和二进制流 1)、文本流:文本流是指在流中流动的数据是以字符形式出现int sscanf(char const *string, char const *format, ...);
4、部分Demo
#include #include /** 如果没有找到打开的文件 **/ int main() { FILE *input; input = fopen("data20", "r"); if (input == NULL) { perror("data3"); exit(EXIT_FAILURE); } return 0; } /** 1111deMacBook-Pro:Music a1111$ gcc -g fopen.c -o fopen 1111deMacBook-Pro:Music a1111$ ./fopen data3: No such file or directory **/
#include #include //转换从标准输入读入的数字 int read_int() { int value; int ch; while ((ch = getchar()) != EOF && isdigit(ch)) { value *= 10; value += ch - '0'; } return value; } int main() { int value = read_int(); printf("value is %d\n", value); return 0; } /** 1111deMacBook-Pro:Music a1111$ gcc -g getc.c -o getc 1111deMacBook-Pro:Music a1111$ ./getc 1233 value is 1233 1111deMacBook-Pro:Music a1111$ **/ ~
#include #define MAX_LENGTH 1024 //复制文件 void copylines(FILE *input, FILE *output) { char buffer[MAX_LENGTH]; while (fgets(buffer, MAX_LENGTH, input) != NULL) fputs(buffer, output); } int main() { FILE *input = fopen("data2", "r"); if (input != NULL) { FILE *output = fopen("data3", "w"); if (output != NULL) { copylines(input, output); fclose(output); } else puts("data3 is NULL"); fclose(input); } else puts("data2 is NULL"); return 0; }
#include int main() { char str[512] = {0}; sscanf("123456", "%4s", str); printf("str is %s\n", str); //读到大写字母为止 sscanf("123aaadf4aD45dbcdBDD", " %[^A-Z]", str); printf("str is %s\n", str); return 0; } /** 1111deMacBook-Pro:Music a1111$ vim sscanf.c 1111deMacBook-Pro:Music a1111$ gcc -g sscanf.c -o sscanf 1111deMacBook-Pro:Music a1111$ ./sscanf str is 1234 str is 123aaadf4a **/
#include #include //格式化数据输入到文本 FILE* stream; int main(void) { int i = 15; double fp = 15.5; char s[] = "hello word"; char c = '\n'; stream = fopen("fprintf.txt", "w"); fprintf(stream, "%s%c", s, c); fprintf(stream, "%d\n", i); fprintf(stream, "%f\n", fp); fclose(stream); return 0; } /** hello word 15 15.500000 **/
#include //格式化输入数据到文本 int main() { FILE* fp; int i = 117; char* s = "chenyu"; fp = fopen("text.dat", "w"); fputs("total", fp); fputs(":", fp); fprintf(fp, "%d\n", i); fprintf(fp, "%s", s); fclose(fp); return 0; } /** total:117 chenyu **/
#include //ftell 用于得到文件位置指针当前位置相对于文件首的偏移字节数 int main(void) { FILE *stream; stream = fopen("MYFILE.TXT", "w+"); fprintf(stream, "This is a test"); printf("The file pointer is at byte %ld\n", ftell(stream)); fclose(stream); return 0; } /** 1111deMacBook-Pro:Music a1111$ vim ftell.c 1111deMacBook-Pro:Music a1111$ gcc -g ftell.c -o ftell 1111deMacBook-Pro:Music a1111$ ./ftell The file pointer is at byte 14 **/int fprintf(FILE *stream, char const *format, ...);
如对本文有疑问, 点击进行留言回复!!
网友评论