Archie Archie - 1 year ago 72
C Question

How to make a C program that can read a data and copy some in a variable?

I'm a student, I am wondering...
How can I make a program that can Get some data from my text file to a variable on my program and print them

Example:

My Text File



I,Ate,Cookies
She,Drink,Coffee
Tom,Wears,Pyjamas


My code



main()
{
FILE *fp=fileopen("c:\\textfile.txt","r");
char name[20],action[20],item[20];
prinf("Enter name: \n");
scanf("%s",&name);

/* I dont Know what to do next */
}





I though about some checking code:

if (name==nametxt) /*nametxt is the first line on the text file */
{
printf("%s\n %s\n %s\n",name,action,item);
}


If the name is "I",the output would look like this :


Enter name:
I
I
Eat
Cookies


A help will satisfy my curiosity thanks in advance

Answer Source
  • You are reading characters from file until you receive new line character (\n) or fill an array, then you return characters stored in an array passed by caller.

  • From this returned array you may get separated values with strtok.

  • Repeat until you receive 0 from getline (Getline received EOF from file.)

Here is simple example with your own getline function which you may modify.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int getline(char s[],int lim, FILE * fp)
{
    int c, i;
    for (i=0; i < lim-1 && (c=fgetc(fp))!=EOF && c!='\n'; ++i)
    {
        s[i] = c;
    }
    if (c == '\n')
    {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

int main()
{
    FILE * fp = fopen("c:\\textfile.txt", "r");

    char line[100];
    char * ptr;

    while (getline(line, 100, fp))
    {
        ptr = strtok(line, ",");

        while( ptr != NULL )
        {
           printf(" %s\n", ptr);

           ptr = strtok(NULL, ",");
        }
    }

    return 0;
}

Output

I
Ate
Cookies

She
Drink
Coffee

Tom
Wears
Pyjamas

Storing strings into variable isnt tough, here is an example

strcpy(name, ptr);

But be careful, writing outside of bounds have undefined behavior.

strncpy(name, ptr, 100); You can limit number of copied characters with strncpy, but be careful, this function is error-prone.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download