Reputation: 1632
I've got a file with 2-3 lines, and every line I want to store in a char* variable, then translate it and store it to other appropriate variables.
not in unix, just in c, there's a fscanf(%d,%s,%s, 1,2,3); and thats it, but in unix it is somewhat weird.
For example: a abc 12 12
Storing it in char msg[20], and then msg[20] will be stored in 4 variables, one char, one char* and two integers. How can It be done?
Here what I got so far:
int ret_in, in1,file;
char buffer1[BUF_SIZE];
int i =0;
char fn[5] = "file";
char msg[20];
file = open(fn,O_WRONLY|O_CREAT,0644);
//msg = "test";
while(((ret_in = read (file, &buffer1, BUF_SIZE)) > 0))
{
for(i; i<ret_in; i++)
{
if(buffer1[i]!='\n')
msg[i] = buffer1[i];
}
}
printf("%s", msg); //TEST: check msg
close(file);
It stores it fine in the msg variable, but if it composed of 4 'items' i want to store in different variables, how can I do it efficiently?
Upvotes: 1
Views: 3103
Reputation: 21316
You can use fopen()
to open a file and get a pointer to a file stream. This pointer can be passed to fgets()
to retrieve lines from the file and store them in a buffer. This buffer can then be parsed by using sscanf()
.
Here is an example of how this might work. Note that here I am using arrays to store the components of the fields from each line; you may have different requirements.
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINES 100
int main(void)
{
FILE *fp = fopen("my_file.txt", "r");
if (fp == NULL) {
perror("Unable to open file");
exit(EXIT_FAILURE);
}
char buffer[1000];
char id[MAX_LINES];
char msg[MAX_LINES][10];
int val_a[MAX_LINES];
int val_b[MAX_LINES];
size_t lines = 0;
while (fgets(buffer, sizeof buffer, fp) != NULL) {
if (sscanf(buffer, "%c%9s%d%d",
&id[lines], msg[lines], &val_a[lines], &val_b[lines]) == 4) {
++lines;
}
}
for (size_t i = 0; i < lines; i++) {
printf("Line %zu: %c -- %s -- %d -- %d\n",
i+1, id[i], msg[i], val_a[i], val_b[i]);
}
fclose(fp);
return 0;
}
Using this text file as input:
A abc 12 34
B def 24 68
C ghi 35 79
gives the following output:
Line 1: A -- abc -- 12 -- 34
Line 2: B -- def -- 24 -- 68
Line 3: C -- ghi -- 35 -- 79
Upvotes: 1