从文件流在C获取数据 [英] Getting data from file stream in c

查看:161
本文介绍了从文件流在C获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想中检索出的数据文件指针,并成为一个字符串。什么是确定字符串缓冲区大小的最好方法?

I am trying to retreive data out of a FILE pointer and into a string. What is the best way to determine the size of the string buffer?

char string[WHAT_SIZE?];
FILE *fp;
fp = fopen("info.dat", "r");

fgets(string, sizeof string, fp);

我是否设置缓冲区大小的东西,我认为是适合于特定的文件?或者是有一个更有效的方式做到这一点,而不使用字符串与非可变的缓冲区大小?

Do I set the buffer size to something I think is suitable for that particular file? Or is there a more efficient way to do this without using strings with non variable buffer sizes?

推荐答案

在一般情况下,你只需要选择一个大小和它去吧。底座上最大的选择期望线路长度或记录长度,或类似的东西,具体到输入类型。只需确保检查返回codeS,当线路较长比预期处理此案。

In general, You just have to pick a size and go with it. Base the choice on max expected line length or record length or something like that specific to the input type. Just make sure to check return codes and handle the case when the line is longer than you expect.

有一些技巧,你可以玩得到一个确切的尺寸,但我不记得有过在实践中使用这些:

There are a few tricks you could play to get an exact size, however I can't remember ever having to use these in practice:


  1. 做一个FTELL,成炭炭阅读,计数,直到你得到一个换行符,然后分配足够的内存,fseek的倒带,读整行。

  1. Do a ftell, read char by char, counting until you get to a newline, then allocate enough memory, fseek to rewind, and read the whole line.

做一个fseek的到文件的末尾找到的大小,再倒回和一次读取整个事情到一个单一的缓冲区。

Do a fseek to the end of the file to find the size, then rewind and read the whole thing at once into a single buffer.

这篇关于从文件流在C获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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