diff --git a/5/io/fmemopen.c b/5/io/fmemopen.c new file mode 100644 index 0000000..33221da --- /dev/null +++ b/5/io/fmemopen.c @@ -0,0 +1,6 @@ +#include + +int main(void) { + // TODO + return 0; +} diff --git a/5/io/fopen.c b/5/io/fopen.c new file mode 100644 index 0000000..a262420 --- /dev/null +++ b/5/io/fopen.c @@ -0,0 +1,45 @@ +#include +#include +#include + +#define RWRR S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH + +int main(void) { + + int fd = open("test/filefp", O_RDWR | O_CREAT | O_TRUNC, RWRR); + + if(fd == -1) { + printf("open file error filefp\n"); + return -1; + } + + FILE *fp = fdopen(fd, "w+"); + char buf[1024]; + + if(setvbuf(fp, buf, _IOFBF, 1024)) { + printf("setvbuf error\n"); + return -1; + } + + if(ferror(fp)) { + printf("io stream error\n"); + return -1; + } + + if(feof(fp)) { + printf("arrive the end of the file\n"); + } + + putc('H', fp); + fputc('Y', fp); + + fputs(" Hello World!", fp); + + fflush(fp); + + fclose(fp); + + close(fd); + + return 0; +} diff --git a/5/io/fread.c b/5/io/fread.c new file mode 100644 index 0000000..494cc16 --- /dev/null +++ b/5/io/fread.c @@ -0,0 +1,40 @@ +#include +#include +#include + + +int main(void) { + FILE *fp = fopen("./test/filefp", "r+"); + + char buf[1024]; + + char *pbuf = fgets(buf, 1024, fp); + + printf("buf: %s\n", buf); + + fseek(fp, 0, SEEK_END); + + fprintf(fp, "num: %d", 123456); + + fpos_t off; + + fgetpos(fp, &off); + + printf("off: %lu\n", off); + + int fd = fileno(fp); + + struct stat st; + + if(fstat(fd, &st) < 0) { + printf("stat error fd\n"); + return -1; + } + + printf("dev: %ld\n", st.st_dev); + + fclose(fp); + close(fd); + + return 0; +} diff --git a/5/io/test/filefp b/5/io/test/filefp new file mode 100644 index 0000000..9b3a0d5 --- /dev/null +++ b/5/io/test/filefp @@ -0,0 +1 @@ +HY Hello World!num: 123456num: 123456num: 123456 \ No newline at end of file diff --git a/5/io/tmpfile.c b/5/io/tmpfile.c new file mode 100644 index 0000000..370e851 --- /dev/null +++ b/5/io/tmpfile.c @@ -0,0 +1,34 @@ +#include + +int main(void) { + char buf[L_tmpnam]; + + char *pbuf = tmpnam(buf); + + printf("tmpnam: %s\n", pbuf); + + FILE *fp = tmpfile(); + + if(fp == NULL) { + printf("create tmp file error\n"); + return -1; + } + + fputs("Hellow World!", fp); + rewind(fp); + + char buf2[1024]; + + if(fgets(buf2, sizeof(buf2), fp) == NULL){ + printf("fgets error\n"); + return -1; + } + + fputs(buf2, stdout); + + fclose(fp); + + + + return 0; +}