0

I am trying to write a program that loads numbers in a text file into an array. The text file is called "numbers" and the numbers are in the following format: 3,49,52,40,34 etc..

When I try to run the program, I get a "program is not responding error". Could anyone please point out what I'm doing wrong? Many thanks.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 32

int main (void) {

    FILE* fp;
    fp = fopen ("numbers.txt", "r");
    if (fp == NULL)
        puts ("No data in file");
        return 0;

    int n = 0;
    int i = 0;
    int j = 0;
    int a[MAX];

    while (fscanf(fp, "%d, ", &n) > 0) {
        a[i++] = n;
    }

    fclose (fp);

    printf ("Data loaded");

    for (j = 0; j < MAX; j++) {
        printf ("%d", a[j++]);
        printf ("THE END");
    }
    return 0;
}
3
  • You forgot the bracket in the if condition which causes the program to return without closing the file handle. Commented Mar 28, 2013 at 20:15
  • 1
    Missing {} after your if (fp == NULL) means you'll always execute the return 0. Commented Mar 28, 2013 at 20:15
  • thank you so much! I can;t believe i missed that Commented Mar 28, 2013 at 20:19

2 Answers 2

2

Put the bracket in the if condition:

FILE* fp;
fp = fopen ("numbers.txt", "r");
if (fp == NULL)
{
    puts ("No data in file");
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

1
if (fp == NULL)
    puts ("No data in file");
    return 0;

Same as:

if (fp == NULL)
    puts ("No data in file");
return 0; //returned already

Your program already returns without reading from the file.

You should do

if (fp == NULL)
{  
    puts ("No data in file");
    return 0; 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.