Zilore Mumba
Zilore Mumba

Reputation: 1540

How do I read numbers in C?

I have a very basic C program which I am not able to get results from. I come from the Fortran world where number crunching is straight forward and the language is non cryptic. I have gone through many C tutorials, and their treatment of processing numerical data, as opposed to strings, in C is not very comprehensive. I have tried my program on three examples data sets (integers, floats and a set of float with three variables (attached int, floats, array)-Unfortunately I do not seem to be able to attach my data. However any example data would do. In my trial data, the first file (integers) has 10 lines of single integer value per line; file two has 10 values of a single float value per line and file three has about 3000 lines of latitude, longitude and a value per line, with a header.

The program compiles and executes, but does not give me results. I would appreciate help

#include <stdio.h>

void main()
{
FILE *f;
char buff[1000],infile[16]="h900_28Mar09.txt";

f=fopen("infile","r");
fgets(buff, 26, (FILE*)f);
printf("%s\n", buff);

while (fgets(buff, 35, (FILE*)f)!=NULL)
 {
   printf("%s\n",buff);
 }
fclose(f);
}

[enter link description here][4]

Upvotes: 1

Views: 105

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50812

You probably wanted this:

#include <stdio.h>

int main()
{
  FILE *f;
  char buff[1000];

  f=fopen("h900_28Mar09.txt", "r");

  if (f == NULL)
  {
    printf("Can't open file\n");
    return 1;
  }

  while (fgets(buff, 35, f) != NULL)
  {
    printf("%s\n",buff);
  }

  fclose(f);
}

This program just opens the file h900_28Mar09.txt and reads and display it line by line.

Alternative way:

...
char buff[1000], infile[] = "h900_28Mar09.txt";

f = fopen(infile,"r");
...

Upvotes: 2

Related Questions