首先对此进行说明,这不是一个完整的解决方案,但我认为它会帮助您解析文件。也代替
将它们存储到一个数组中,例如“int process[10]”
我认为最好将它们存储在动态数组中,否则您需要事先知道要提取的列的行数。此代码仅根据您的格式解析文件并打印第一列的值,我认为在您实现动态数组后可以适应您的情况,所以这里是:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/*scan_file: read each of the lines of the file.*/
int scan_file(char *filename)
{
char *line_buf = NULL;
size_t line_buf_size = 0;
ssize_t line_size;
char *next = NULL;
FILE *fp = fopen(filename, "r");
if (!fp) {
fprintf(stderr, "Error opening file '%s'\n", filename);
return 1;
}
/*Get the first line of the file and do nothing with it*/
line_size = getline(&line_buf, &line_buf_size, fp);
while (line_size > 0)
{
//second and subsecuent lines
line_size = getline(&line_buf, &line_buf_size,fp);
if (line_size <= 0)
break;
line_buf[line_size-1] = '\0'; /*removing '\n' */
char *part = strtok_r(line_buf, " ", &next);
if (part)
printf("NUMBER: %s\n", part);
}
// don't forget to free the line_buf used by getline
free(line_buf);
line_buf = NULL;
fclose(fp);
return 0;
}
int main(void)
{
scan_file("file.txt");
return 0;
}
注意:这里我假设文件名为file.txt,您应该将其更改为文件名。
输出:
NUMBER: 1
NUMBER: 2
NUMBER: 3
NUMBER: 4
NUMBER: 5
NUMBER: 6
NUMBER: 7
NUMBER: 8
NUMBER: 9
NUMBER: 10
我这样说是为了让你可以识别printf("NUMBER: %s\n", part);这一行,在这里你可以将其更改为将这个值推入动态数组的东西。