简体   繁体   English

C编程,从文件中读取特定部分

[英]C Programming, Reading specific sections from file

my question is how can I read specific sections from a file? 我的问题是如何从文件中读取特定部分? For instance, if my file was: 454545454 Joe Brown 70 50 40 656565656 David Smith 80 90 100 383838383 George Williams 95 100 80 例如,如果我的文件是: 454545454 Joe Brown 70 50 40 656565656 David Smith 80 90 100 383838383 George Williams 95 100 80

How could I read the first string (9-Digit #), skip over the name, and then read the 3 sets of numbers? 如何读取第一个字符串(9位数字),跳过名称,然后读取3组数字?

Instead of "reading specific sections," read file line by line and save the information you want and discard the others. 而不是“读取特定部分”,而是逐行读取文件并保存所需的信息,然后丢弃其他信息。 scanf is used to read formatted from an external source into program variables. scanf用于将格式从外部源读取到程序变量中。 Since scanf returns the number of successful reads from the source, you can use that to do some error checking. 由于scanf返回从源读取的成功次数,因此可以使用它来进行一些错误检查。

char num_string[STR_LEN];
int numbers[3];
char dummy1[STR_LEN], dummy2[STR_LEN];
int num_read = scanf( "%s%s%s%d%d%d", num_string, dummy1, dummy2, &numbers[0], &numbers[1], &numbers[2] );

if( num_read != 6 )
    // error
else
{
    // do stuff with num_string, and numbers[0]-numbers[2]
}

I think that you could notice that the white space is your sentinel. 我认为您可能会注意到空白是您的前哨。 I'm thinking that maybe you can store the whole file into a char* and asking for this sentinel each time. 我在想,也许您可​​以将整个文件存储为char *并每次都请求此标记。 Other solution could be using atoi (ascii to int) for validate if it's a number or a letter. 其他解决方案可能是使用atoi (从ascii到int)来验证它是数字还是字母。 You can also read about fread and fseek . 您还可以阅读有关freadfseek的信息

I think that the best way is to mix both solution... find each sentinel and try to parse it using atoi. 我认为最好的方法是将两种解决方案混合在一起……找到每个哨兵,然后尝试使用atoi进行解析。

The main idea is that you try to find some pattern in the file that allows you to think the algorithm. 主要思想是您尝试在文件中找到某种模式,以便您思考算法。 In C, most of the times you have to solve the logic by yourself. 在C语言中,大多数时候您必须自己解决逻辑问题。

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM