C - fopen() doesn't work (returns null pointer) [duplicate]

孤者浪人 提交于 2019-12-11 11:43:06

问题


Why does fopen() return a null pointer?

I'm trying to save the parameters after BRIDGE and after LAN (respectively 4 and 5) in cont_br and cont_lan, but fopen() doesn't work...

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

void read_file(char file[]) {

    char cont, *str, *ctrl_str;
    int x=0, cont_br, cont_lan;

    FILE *file_stream;

    if (file_stream = fopen(file, "r")) {

        while( !feof(file_stream) ) { //Check the file dimension
            fgetc( file_stream );
            x++;
        }
        x--;
        str = (char*) malloc(sizeof(char) * x+1);
        fseek(file_stream, 0, SEEK_SET); // Return at the beginning of the file
        fread(str, x, 1, file_stream);
        char delims[] = "#";
        char *result = NULL;
        result = strtok( str, delims);
        while (result != NULL) {
            if (result == "BRIDGE") { //Check the different "blocks" in the txt file
                result = strtok(NULL, delims);
                cont_br = atoi(result);
                printf("Number of bridges: %d\n", cont_br);
            }
            result = strtok(NULL, delims);
            if (result == "LAN") {
                result = strtok(NULL, delims);
                cont_lan = atoi(result);
                printf("Number of Lan: %d\n", cont_lan);
            }
            break; //
        }
    }
    printf("Error: can't open the file! errno: %d\n", errno);
    fclose(file_stream);
}

int main() {
    char file[] = "Config.txt";
    read_file(file);
    return 0;
}

And this is the Config.txt file:

BRIDGE#4#
LAN#5#
192.168.0.1
192.168.1.1
192.168.2.1
192.168.3.1
192.168.4.1
#
LINK#
B1:3000,L1
B1:3001,L2
B1:3002,L3
B2:3000,L4
B2:3001,L5
B3:3000,L1
B4:3000,L3
B5:3000,L2
B2:3002,L3

回答1:


Whenever fopen fails then print the error number (errno).

#include <error.h>

You should include the standard errno.h and print the value of error in your code. Then look at the error code and find the reason.

Example

#include <stdio.h>
#include <errno.h>

int main()
{
    errno = 0;
    FILE *fb = fopen("/home/jeegar/filename", "r");
    if (fb==NULL) {
        printf("Error %d \n", errno);
        printf("It's null");
    }
    else
        printf("working");
    }

This way if fopen fails then it will set the error number. You can find those error number lists in fopen.



来源:https://stackoverflow.com/questions/24081999/c-fopen-doesnt-work-returns-null-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!