c - I can't read data into an array -


i'm trying read data text file , copy them array, code doesn't work. code:

#include <stdio.h> int main(int argc, char *argv[]) {     int i;      file *data;     data = fopen(argv[1], "r");      .......      fclose(data); } 

and when replace

data = fopen(argv[1], "r");` 

with

data = fopen("(the file name)", "r"); 

it works.

this full code

#include <stdio.h> int main(int argc, char *argv[]) { int i; i=0; file *data; data = fopen(argv[1], "r");  while (!feof(data)) {     fscanf(data, "%i", &aa[i]);     i++; }  fclose(data); printf("%i\n", aa[0]); } 

and text file is

3 2 1 2 2 2 3 

you should write basic error checking code might reasonably fail, e.g.:

#include <stdio.h> #include <errno.h>  int main(int argc, char *argv[]) {     int i;     file *data;      if (argc < 2)     {         fprintf(stderr, "missing arguments: %s\n", usage);         exit(1);     }      data = fopen(argv[1], "r");     if (data == null)     {         fprintf(stderr, "fopen('%s') failed, errno = %d, argv[1], errno);         exit(2);     }      .......      fclose(data);      return (0); } 

this way if fopen fails (a) won't crash , (b) useful info why file not opened.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -