简体   繁体   中英

Reading from file doesn't return anything, but it is accessed

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp ;
    int n,i,x[n];

    fp=fopen("fin.txt","r");

    if (fp == NULL) {
        puts("Error opening filename.txt");
        return EXIT_FAILURE;
}

    fscanf("%d",&n);
    for (i=0;i<n;i++)
        fscanf("%d",&x[i]);
    printf("%d ",n);
    fclose(fp);
    return 0;
}

I'm trying to read from a file, although it doesn't print anything. I checked to see if it opens the file, and it does. Although no data returned. Why is that? Input file: 5 3 4 5 8 2 -------------------------------------------EDIT : The file is the project's folder.

You're not calling fscanf correctly.

The first argument to fscanf is a FILE * for the file you want to read from. You've omitted this argument, so the function is taking the string you passed in as the first argument and attempting to read it as a FILE object.

Pass fp as the first arguments in each of the calls.

This also isn't doing what you expect:

int n,i,x[n];

This doesn't mean that the size of the array x is tied to the value of n . It means the size of x is set to the current value of n , which hasn't been assigned a value yet.

Move the declaration of x to after a value has been read in for n .

int rval = fscanf(fp, "%d",&n);
if (rval != 1) return EXIT_FAILURE;
int x[n];
for (i=0;i<n;i++)
    fscanf(fp, "%d",&x[i]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM