简体   繁体   English

从文件中读取不会返回任何内容,但会被访问

[英]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.输入文件:5 3 4 5 8 2 ----------------------------------------- --EDIT :该文件是项目的文件夹。

You're not calling fscanf correctly.您没有正确调用fscanf

The first argument to fscanf is a FILE * for the file you want to read from. fscanf的第一个参数是要从中读取的文件的FILE * 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.您已省略此参数,因此该函数将您传入的字符串作为第一个参数并尝试将其作为FILE对象读取。

Pass fp as the first arguments in each of the calls.fp作为每个调用中的第一个参数传递。

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 .这并不意味着数组x的大小与n的值相关。 It means the size of x is set to the current value of n , which hasn't been assigned a value yet.这意味着x的大小设置为n当前值,它还没有被赋值。

Move the declaration of x to after a value has been read in for n .在为n读入值后,将x的声明移至。

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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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