Reputation: 31
i have a file("career.txt") where each line are composed in this way:
serial number(long int) name(string) surname(string) exam_id(string) exam_result(string);
each line could have from 1 to 25 couple composed by the exam_id(ex: INF070) and the exam_result(ex:30L).
Ex line: 333145 Name Surname INF120 24 INF070 28 INF090 R INF100 30L INF090 24
33279 Name Surname GIU123 28 GIU280 27 GIU085 21 GIU300 R
I don't know how many couple there are in one line(there could be 1, 5 or 25)(so i can't use a for cycle) and i have to read it. How can i read the entire line?
I tried use getline and fgets, and then divide the string with strtok, but I don't know why it doesn't work.
Upvotes: 1
Views: 98
Reputation: 121
If you don't know the maximum number of characters in a line of the text file, one way to read the entire line is to dynamically allocate memory for the buffer as you read the file. You can use the getline function to do this which is a POSIX function. Here is an example of how you can use getline to read a line from a file:
#include <stdio.h>
#include <stdlib.h>
int main() {
char *buffer = NULL;
size_t bufsize = 0;
ssize_t characters;
FILE *file = fopen("file.txt", "r");
if (file == NULL) {
printf("Could not open file\n");
return 1;
}
while ((characters = getline(&buffer, &bufsize, file)) != -1) {
printf("Line: %s", buffer);
}
free(buffer);
fclose(file);
return 0;
}
The getline function works by allocating memory for the buffer automatically, so you don't have to specify a fixed buffer size. It takes three arguments: a pointer to a pointer to a character (in this case, &buffer), a pointer to a size_t variable (in this case, &bufsize), and a pointer to a FILE object representing the file you want to read from. The function reads a line from the file and stores it in the buffer, dynamically allocating more memory if necessary. The getline function returns the number of characters read, which includes the newline character at the end of the line, or -1 if it reaches the end of the file. And in the example above, each line is read and printed. And it is important to release the memory after finished processing the buffer, in this case by free(buffer).
Upvotes: 3