Reading text files into C

Discussion in 'Mac Programming' started by Spanky Deluxe, Nov 12, 2006.

  1. Spanky Deluxe macrumors 601

    Spanky Deluxe

    Mar 17, 2005
    London, UK
    I could really do with some help on this one. For the project I'm working on I need to analyse some data using c. The analysing part seems to be coming on great. However, I can't get my program to read in the data from a file (for the time being I've resorted to typing in all of the data by hand which works fine for the smallish 32 entry data set I'm using for the moment). I tried using fin and fscanf etc as we were taught in our c module a year ago but this didn't seem to work when compiling programs with Xcode in OS X and I got somewhat rebuked on here for trying to use them.

    Could someone help me write a simple bit of code to read data in? My data is stored in a text file in the form of a list of two columns of numbers separated by one or more spaces. I can fiddle with the format of the data file in excel so I can give it commas to seperate variables or whatever. All I need is something to read data in. Later on I'll want something to write data out but for the moment that's not really a priority.
    It doesn't have to be anything fancy, nor does it have to be particularly efficient, just *something*!

    Sorry if I appear to be grovelling, I'm at a loss right now and could really do with some help!!
  2. rand0m3r macrumors regular

    Jun 30, 2006
    scanf should be fine. just make sure the input parameter is "stdin". then when you run the binary on the command-line, remember to < file.txt .

    fgets can also be used to read in a string at a time.
  3. pilotError macrumors 68020


    Apr 12, 2006
    Long Island
  4. PrOeliuM macrumors member

    Jul 31, 2005
    Some sample code could look like:

    FILE *fp // create a file pointer that will reference your text file
    char buf[80] // what you'll read into
    int n1, n2 // if you're reading two numbers 
    fp = fopen("nameoffile", "r") // open up the file you're looking for
    if (fp == NULL) // problem opening the file
     exit(1) // quit
    while (fgets(buf, 80, fp) != NULL && !feof(fp)) // keep reading till you reach the end
    sscanf(buf, "%d %d", &n1, &n2); // buf is one line of the input file which contained two columns, so read in each var
    printf("n1 = %d n2 = %d\n", n1, n2); // print the results to stdout

Share This Page