一个char *或**字符可以伪装成一个FILE *? [英] Can a char * or char ** masquerade as a FILE *?

查看:410
本文介绍了一个char *或**字符可以伪装成一个FILE *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,我经常要处理来自从字符串数组以同样的方式读取文件和数据读取数据。通常从文件中读取是生产与字符串是测试。我风写了很多code像这样的:

In C, I often want to handle data read from a file and data read from an array of strings the same way. Usually reading from a file is for production and from strings is for testing. I wind up writing a lot of code like this:

void handle_line(char *line, Things *things) {
    ...
}

Things *read_from_chars(char *lines[]) {
    Things *things = Things_new();

    for (int i = 0; lines[i] != NULL; i++) {
        handle_line(lines[i], things);
    }

    return things;
}

Things *read_from_input(FILE *input) {
    char *line = NULL;
    size_t linelen = 0;

    Things *things = Things_new();

    while (getline(&line, &linelen, input) > 0) {
        handle_line(line, things);
    }

    return things;
}

这是重复劳动。

有没有一种办法可以让一个字符串数组伪装成 FILE * 指针?或相反亦然?或者是有处理这一问题的一个更好的模式?

Is there a way I can make an array of strings masquerade as a FILE * pointer? Or vice-versa? Or is there a better pattern for dealing with this problem?

有关奖励积分:解决方案应该让的char * 的char ** 与标准文件功能,如可用与fgets 函数getline

For bonus points: the solution should make char * or char ** usable with the standard file functions like fgets and getline.

推荐答案

有一个非标准的功能 fmemopen ,让你打开一个char []读取或写入。它是在GNU libc中的大多数版本,我想,大多数版本的Linux。

There's a nonstandard function fmemopen that lets you open a char[] for reading or writing. It's available in most versions of GNU libc, I think, and most versions of Linux.

(这允许您从读取或写入到一个字符串,而不是你问的字符串数组)。

(This lets you read from or write to a single string, not the array of strings you asked about.)

这篇关于一个char *或**字符可以伪装成一个FILE *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆