uydo(kiboga) said:
Hello,
I have to write a program that reads from a text file into a structure.
Every line in the file looks like this:
"1234","first.last","password"
I dont know if there is a function to pass the above line into a structure
emp{"1234","first.last","password"}.
If this is not the case, what is your suggestion to do the job?
There is no pre-built function to do this task. You can
write one yourself, something like
struct emp line_to_emp(char *line) {
struct emp *new;
new = malloc(sizeof *new);
if (new != NULL) {
new->eins = duplicate(strtok(line, ",\""));
new->zwei = duplicate(strtok(NULL, ",\""));
new->drei = duplicate(strtok(NULL, ",\""));
if (new->eins == NULL || new->zwei == NULL
|| new->drei == NULL) {
free (new->eins);
free (new->zwei);
free (new->drei);
free (new);
new = NULL;
}
return new;
}
.... along with the "helper" function
char *duplicate(const char *old) {
char *new;
new = (old == NULL) ? NULL : malloc(strlen(old) + 1);
if (new != NULL)
strcpy (new, old);
return new;
}
Now, this is not necessarily the best way to proceed.
It may not even meet your needs -- you haven't stated
exactly what it is you're trying to do, and I'm just
making plausible guesses from one "like this" case. In
particular, this method assumes
- There are no embedded commas in the fields of
interest,
- You really do want to get rid of the quotation
marks,
- The strtok() function is not being used at a
higher level when line_to_emp() is called,
- It is permissible to modify the input line as
a by-product of filling in the struct.
If these assumptions are not met, you'll need to work
harder. Even if they *are* met, you may want to do things
differently anyhow. The number of different plausible
variations on the theme of "chop a line into fields" is
large -- and that may be one of the reasons that no pre-
built function exists to do the task.
<off-topic>
My use of `new' as an identifier is deliberate, in
keeping with my view that code should be either C or C++
but not "C/C++". Use a language, not a patois!
</off-topic>