linux高级环境编程-标准IO

2017-06-25  本文已影响21人  lifesmily

标准IO也是带缓存的IO,它们的操作是围绕流进行,而之前的不带缓存IO操作是围绕文件描述符的,标准IO还是基于文件IO或者说系统IO。

image.png

预读
http://hongyilinux.blog.51cto.com/8030513/1746199
https://segmentfault.com/a/1190000008228426
http://www.yeolar.com/note/2012/05/16/linux-advanced-io/

常用函数API

FILE *fopen(const char *path, const char *mode)
int fclose(FILE *fp)
int fgetc(FILE *stream)
int fputc(int c, FILE *stream)
char *fgets(char *s, int size, FILE *stream)
int fputs(const char *s, FILE *stream)
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)

程序示例:

#include <stdio.h>

int main(int argc, char *argv[])
{
    FILE *fp;

    fp = fopen("stdio.log", "w+");
    if (fp == NULL) {
        printf("File create fail...\n");
        return -1; 
    } else {
        printf("File create success...\n");
    }
    
    /* fwrite() function */ 
    char buffer_1[] = "This is fwrite DEMO..."; 
    size_t wr_size = 0; 
    wr_size = fwrite(buffer_1, 1, sizeof(buffer_1), fp); 
    printf("wr_size = %d\n", wr_size); 

    /* fputs() function */ 
    char buffer_2[] = "\nThis is fputs DEMO...\n"; 
    int fputs_status = 0; 
    fputs_status = fputs(buffer_2, fp); 
    printf("fputs_status = %d\n", wr_size); 
    
    /* puts function */
    char buffer_3[] = "This is puts DEMO..."; 
    puts(buffer_3);

    /* fputc function */
    char buffer_4[] = "This is fputc DEMO...\n";
    int ret;
    for (int i = 0; i < sizeof(buffer_4); i++) {
        ret = fputc(buffer_4[i], fp);
        printf("%c", ret);
    }

    /* putc function */
    char buffer_5[] = "This is putc DEMO...\n";
    for (int i = 0; i < sizeof(buffer_5); i++) {
        ret = fputc(buffer_5[i], fp);
        printf("%c", ret);
    }    
    fclose(fp);   
    return 0; 
}
进一步分析:

IO操作可以分为非格式IO和格式IO,非格式化IO有以下三种,

image.png image.png

buf为缓冲区地址,gets表示从标准输入读,而fgets从指定的流读,fgets必须指定缓冲区长度n,最后一个为null,能读入n-1个字符,若一行长度大于n,则返回一个不完整的行。gets没有指定缓冲区长度会导致可能的溢出,一般弃用。

image.png

fputs将一个以null字节终止的字符串写道指定的流,不一定每次一行,要看有没有换行符,和上面的读fgets对应。
puts将一个null字节终止的字符串写到标准输出,同时会写入一个换行符。put尽量不使用。

一般有以下两种常见用法,读写一个数组和读一个结构。

#include <stdio.h>
  
int main ()
{
    FILE *fp = fopen ("output.txt", "w");
    float data[10] = {0, 12, 1.414, 3.562, 43213, 4214};
    if (fwrite (data, sizeof(float), 10, fp) != 10)
    {
        perror ("fwrite error: ");
        return -1;
    }
    return 0;
}
#include <stdio.h>
#include <string.h>
 
#define NAMESIZE 1024
  
struct Str_tmp
{
    short count;
    long total;
    char name[NAMESIZE];
};
  
int main ()
{
    struct Str_tmp item;
    scanf ("%s", item.name);
    item.count = strlen (item.name);
    item.total = 1024;  
      
    FILE *fp = fopen ("output.txt", "w");
  
    if (fwrite (&item, sizeof(item), 1, fp) != 1)
    {
        perror ("fwrite error: ");
        return -1;
    }
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读