Home  >  Q&A  >  body text

c++ - C语言文件读写基本问题

文件读写最简单问题,编译器是Eclipse C++,fopen函数总是返回空指针,怎么回事?

#include <stdio.h>
#include <fstream>
using namespace std;

int main(){
    FILE *fp;
    fp=fopen("1.txt","r+");
    if(fp==NULL){
        printf("there is no character.");
    }
    char buff[255];
    fscanf(fp,"%s",buff);
    printf("%s",buff);
}

文件目录如下

怪我咯怪我咯2714 days ago536

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 15:08:12

    Because the 1.txt file cannot be found. That is, the working directory of program execution is not src.
    Did you directly click the Run or Debug button to execute it? Then click the small triangle next to the button and select your Run or Debug Configuration. The second tab has the working path, which is usually a preset variable workspace_loc, which is the directory representing the workspace.

    You can either change the settings, put 1.txt in that path, or write the absolute path in the code.

    In addition, the global variable errno will record the reason for fopen failure.

    reply
    0
  • Cancelreply