Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Spanky Deluxe

macrumors demi-god
Original poster
Mar 17, 2005
5,285
1,789
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!!
 

rand0m3r

macrumors regular
Jun 30, 2006
115
1
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.
 

PrOeliuM

macrumors member
Jul 31, 2005
30
0
Some sample code could look like:

Code:
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
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.