I want to read a datafile which consits of 5 coloums and 4 rows, which consists of numbers seperated by commas.
The first line of the data file looks like this: 103343, 24, 55, 24,12.
I have started my program by allowing to input the file in my program, however i dont know how i can read it.
My program at the moment looks like:

         FILE *my_in;
int count=0;


my_in= fopen("C:\\datafile.txt", "rt"); // read only  
 if(my_in==NULL)

                printf("\nError opening input file, program exiting\n");
                printf("\nType a number & press the enter key to finish");
                scanf("%d",&count);
                return(1); /* program aborts returning 1 to operating system */
                }


}

Recommended Answers

All 3 Replies

The simplest approach would be fgets() and strtok(). Here's a quickie example:

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

int main(void)
{
    FILE *in = fopen("test.txt", "r");

    if (in) {
        char line[BUFSIZ];
        char *tok;
        int i = 0;

        while (fgets(line, sizeof line, in)) {
            line[strcspn(line, "\n")] = '\0'; /* Trim the newline if present */
            tok = strtok(line, ",");

            printf("Line #%d\n", ++i);

            while (tok) {
                printf("\t'%s'\n", tok);
                tok = strtok(NULL, ",");
            }
        }
    }

    return 0;
}

Thanks, but when i implement that in my program it doesnt display the values like i want them to. Instead of seperating by a comma it shows

'8'
'5'
'7'

I want the program to show 8, 5, 7

That program was an example, not a solution to your exact problem. You're supposed to learn from it and use it as a template for constructing a program that does solve your exact problem. I won't do your work for you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.