如何FGETS()从在C文件中的特定行? [英] How to fgets() a specific line from a file in C?

查看:300
本文介绍了如何FGETS()从在C文件中的特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我试图找到一种方法,与fgets()在用C一个文本文件中的某一行,该行的内容复制到一个更持久的缓冲区:

So, I'm trying to find a way to fgets() a specific line in a text file in C, to copy the contents of the line into a more permanent buffer:

从本质上讲,我想知道是否有办法做到这一点,而不类似于以下code的内容:

Essentially, I was wondering if there was a way to do that without something similar to the following code:

FILE *fp;
fp = fopen(filename, "r");

char line[256];
char * buffer;
int targetline = 10;
while( targetline > 0)
{
    fgets(line, 256, fp)
}

buffer =(char*)malloc(sizeof(char) * strlen(line));
strcpy(buffer, line);

所以基本上我不想通过文件N-1次刚去的第n行迭代...它只是似乎并不非常有效的(而且,这是功课,我需要得到一个100 %哈哈)。

So basically I don't want to iterate through the file n-1 times just to get to the nth line... it just doesn't seem very efficient (and, this being homework, I need to get a 100% haha).

任何帮助将是AP preciated。

Any help would be appreciated.

推荐答案

除非你知道更多的东西有关文件,你不能随意访问特定行。新线由行结束字符的presence分隔并且它们可以,一般来说,发生在任何地方。文本文件不配备了的地图首页的,它会让你跳到第n 行。

Unless you know something more about the file, you can't access specific lines at random. New lines are delimited by the presence of line end characters and they can, in general, occur anywhere. Text files do not come with a map or index that would allow you to skip to the nth line.

如果你知道,比方说,文件中的每一行是一样长,那么你可以使用随机访问跳转到一个特定的行。如果没有这种额外的知识,你根本别无选择,只能通过整个文件迭代,直到你达到你想要的线路。

If you knew that, say, every line in the file was the same length, then you could use random access to jump to a particular line. Without extra knowledge of this sort you simply have no choice but to iterate through the entire file until you reach your desired line.

这篇关于如何FGETS()从在C文件中的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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