Usenet.com

www.Usenet.com

Group Index

Comp Thread Archive from Usenet.com

<-- __Chronological__ --> <-- __Thread__ -->

Re: C programming - reading from a file - help request!



In article <[EMAIL PROTECTED]>, Benjamin Robson
<[EMAIL PROTECTED]> writes

A little more use of indentation and less use of newlines would help.

>int main(void)
>{
>char line[101], filename[101];
>char*line_ptr;
always, always initialise pointers.
>struct node
>            {
>            int id;
>            double x, y;
>            };
>struct node node_array[100];
>int no_nodes = 0, no_values;
>FILE*input_stream;
>fprintf(stdout, "Enter file name:");
>fscanf(stdin, "%s", filename);
>if ((input_stream = fopen(filename, "r")) !=NULL)
but what happens if it isn't, i.e. the file is not opened for reading?
Try rewriting as:

if((input_stream = fopen(filename, "r")) == NULL){
        puts("Could not open input file");
        return EXIT_FAILURE;
        }

and remove the following brace as the rest now uses a file that could be
opened. I.e. eliminate the bad case rather than check you have the good
one.
>            {
>            fgets(line, sizeof(line), input_stream);
>            while(((line_ptr = fgets(line, sizeof(line), input_stream))
>!=NULL)
but this already eliminates cases where line_ptr is NULL so there is no
point in latter checks for it. Oh I see, you are doing all your
processing inside the while. Don't do that, learn to write simple short
statements it makes you code much easier to follow.
>&&
>                          ((no_values = sscanf(line, "%d %lf %lf",
>&node_array [no_nodes].id,
>&node_array [no_nodes].x,
>&node_array [no_nodes].y)) = =3)) no_nodes++;
>
>if ((line_ptr !=NULL)&&(no_values !=3))
{
>
>            fprintf(stdout, "Error reading line %s\n", line);
              return EXIT_FAILURE;
}
>else
>            if(line_ptr= =NULL)
{
>               fprintf(stdout, "End of file found\n");
              return EXIT_FAILURE;
}
>}
return EXIT_SUCCESS;
>}

-- 
Francis Glassborow      ACCU
If you are not using up-to-date virus protection you should not be reading
this. Viruses do not just hurt the infected but the whole community.
-- 
comp.lang.c.moderated - moderation address: [EMAIL PROTECTED]



<-- __Chronological__ --> <-- __Thread__ -->


Usenet.com



Please check out one of the premium Usenet Newsgroup Service Providers below for access to Usenet.