fprint()将格式化信息输出到指定的文件流
int fprintf(FILE *stream, const char *format, …);
int main(int argc, char const *argv[])
{
FILE *fp;
fp = fopen("1.txt", "wb");
char *str = "this is a string";
fprintf(fp, "hello, %s\n", str);
fclose(fp);
return 0;
}
printf():将格式化信息输出到标准输出文件stdout
sprintf():将格式化信息输出到一个字符串
int sprintf(char *str, const char *format, …);
int main(int argc, char const *argv[])
{
char *str = "this is a string";
char str1[32] = {0};
sprintf(str1, "hello, %s\n", str);
printf("%s", str1);
return 0;
}
fwrite():以二进制位方式写入文件
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
int main(int argc, char const *argv[])
{
FILE *fd;
fd = fopen("1.txt", "wb");
char *str = "hello, this is a string!";
size_t ret = fwrite(str, strlen(str), 1, fd);
printf("%ld\n", ret);
fclose(fd);
return 0;
}
fread():以二进制位方式读文件
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
int main(int argc, char const *argv[])
{
FILE *fd;
fd = fopen("1.txt", "rb");
char buff[128];
size_t ret = fread(buff, sizeof(buff), 1, fd);
printf("%s\n", buff);
fclose(fd);
return 0;
}
put系列输出
#include <stdio.h>
int fputc(int c, FILE *stream);
int fputs(const char *s, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);
int puts(const char *s);
fputc将字符c输出到文件流,成功返回字符,失败返回eof或errno
注意此处参数c的类型是int而不是char, 是输入字符的ASCII码值
int main(int argc, char const *argv[])
{
int a = 65;
fputc(a, stdout); //输出A
return 0;
}
其实putc()和fputc()应该是完全相同的
fputs将字符串输出到文件流
一般用于指定文件写入操作
int main(int argc, char const *argv[])
{
FILE *fp;
fp = fopen("1.txt", "wb");
char *str = "this is a string";
fputs(str, fp);
fclose(fp);
return 0;
}
putchar()和puts():分别是将字符、字符串输出到标准输出流
fputc('a', stdout);
fputs("string", stdout);
putc('b', stdout);
puts("string"); //自动换行
putchar('c');
get系列输入
int fgetc(FILE *stream);
char *fgets(char *s, int size, FILE *stream);
int getc(FILE *stream);
int getchar(void);
int ungetc(int c, FILE *stream);
fgetc()从文件流读入一个字符,成功返回字符的ASCII,失败返回eof或errno
getc()等价于fgetc(),不同的是它可以被实现为对流进行多次评估的宏
getchar()等价于getc(stdin),从标准输入流取一个字符
int main(int argc, char const *argv[])
{
int a, b, c;
char str[20] = {0};
a = fgetc(stdin);
b = fgetc(stdin);
c = fgetc(stdin);
fgets(str, sizeof(str), stdin);
putchar(a);
putchar(b);
putchar(c);
fputs(str,stdout);
return 0;
}
ungetc():将一个字符退回到文件流中,该字符将由下一个读取文件流的函数得到
int main(int argc, char const *argv[])
{
int i = 0;
char ch;
puts("Input an integer followed by a char:");
while((ch = getchar()) != EOF && isdigit(ch))
{
i = 10 * i + ch - 48; // 转为整数
}
if (ch != EOF)
{
ungetc(ch,stdin); // 把一个字符退回输入流
}
printf("i = %d, next char in buffer = %c\n", i, getchar());
return 0;
}
hohj@ubuntu20-10:~/Documents/C/sys$ ./sysio
Input an integer followed by a char:
123abc
i = 123, next char in buffer = a