【问题标题】:File Pointer Not Being Assigned a Value When Using fopen()使用 fopen() 时文件指针未赋值
【发布时间】:2020-01-10 19:29:00
【问题描述】:

我正在尝试编写一个简单的 C 程序,该程序将从 csv 文件中读取数据并对这些数据执行一些计算。

不幸的是,我的文件指针fptr 在调用fopen() 后没有被赋值。我知道在单步执行 VS 2017 的调试器后就是这种情况。然而我不知道为什么会这样。这是一个大问题,意味着每当我尝试从文件中读取数据或关闭文件时,我的程序都会抛出一些非常讨厌的异常。

我的代码如下:

ma​​in.c

#include<stdio.h>
#include <stdlib.h>         // For exit() function
#include"constants.h"       //For access to all project constants

/***************************************************************************************************************
To keep the terminal from automatically closing
Only useful for debugging/testing purposes
***************************************************************************************************************/
void preventTerminalClosure() {
    //flushes the standard input 
    //(clears the input buffer) 
    while ((getchar()) != '\n');
    printf("\n\nPress the ENTER key to close the terminal...\n");
    getchar();
}

/***************************************************************************************************************
Read the given input file
***************************************************************************************************************/
void readInputFile(char fileName[]) {
    FILE *fptr;
    char output[255];

    //open the file
    if (fptr = fopen(fileName, "r") != NULL) {          //read file if file exists
        //fscanf(fptr, "%[^\n]", output);
        //printf("Data from the file:\n%s", output);
        printf("<--Here-->");
    }else {                             
        printf("\nERROR 1: File %s not found\n", fileName);
        preventTerminalClosure();
        exit(1);
    }

    fclose(fptr);                       //close the file
}

/***************************************************************************************************************
                                        *   *   *   Main    *   *   *
***************************************************************************************************************/
void main() {
    char testName[MAX_NAME_SIZE];

    printf("Hello World!\n");
    printf("Please enter your name: ");
    scanf("%s", testName);

    printf("It's nice to meet you %s!", testName);

    readInputFile("dummy.txt");

    preventTerminalClosure();   //Debug only

}

我已确定我的假文件确实存在并且位于正确的位置。否则我的代码会碰到readInputFile() 内的else 块。这是我已经彻底测试过的东西。

显然我缺少一些基本的东西来解释这种指针行为;但那是什么,我不确定。任何帮助,将不胜感激! :)

【问题讨论】:

  • 也许 VS 试图在与您预期不同的目录中打开文件。该文件是否与可执行文件在同一目录中?
  • 你缺少一些括号。
  • 你的编译器没有警告你吗?我知道 gcc 和 clang 会,不确定 msvc。
  • if (fptr = fopen(fileName, "r") != NULL) --> if ((fptr = fopen(fileName, "r")) != NULL)

标签: c file file-io


【解决方案1】:

使用括号强制执行顺序,以便fptrNULL 在分配值后与fopen 进行比较:

FILE *fptr;
char output[255];

//open the file
if ( (fptr = fopen(fileName, "r")) != NULL)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 2013-05-16
    • 2011-10-27
    • 2011-10-10
    • 1970-01-01
    相关资源
    最近更新 更多