I have a text file that looks like this:
Process Priority Burst Arrival
1 8 15 0
2 3 20 0
3 4 20 20
4 4 20 25
5 5 5 45
6 5 15 55
7 9 10 70
8 6 15 100
9 5 15 105
10 5 15 115
The columns are separated by tabs. I need to ignore the first line and then all entries from one column store them into an array such as "int process[10]".
I have found this thread :Reading in a specific column of data from a text file in C , however the way is done is very specific to the way the data is set up in the op's question.
thanks.
Give this a try. This grabs all columns you have from the file and is compliant with ansi:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void parseLine(char *line, int *num1, int *num2, int *num3, int *num4 ){
char* temp;
temp = strchr(line,'\t');
temp[0] = '\0';
*num1 = atoi(line);
line = temp + 1;
temp = strchr(line, '\t');
temp[0] = '\0';
*num2 = atoi(line);
line = temp + 1;
temp = strchr(line, '\t');
temp[0] = '\0';
*num3 = atoi(line);
line = temp + 1;
*num4 = atoi(line);
}
int main(void)
{
FILE* fp;
char line[100];
int process[10];
int priority[10];
int burst[10];
int arrival[10];
int i;
int j;
i = 0;
if ((fp = fopen("./yourfile.txt", "r")) == NULL)
{
printf("Error Opening File\n");
exit(1);
}
fgets(line, sizeof(line), fp);
while (fgets(line, sizeof(line), fp))
{
parseLine(line, &process[i],&priority[i],&burst[i],&arrival[i]);
i++;
}
for (j = 0; j < 10; j++){
printf("Process: %d, Priority: %d, Burst: %d, Arrival: %d\n", process[j], priority[j], burst[j], arrival[j]);
}
fclose(fp);
return 0;
}