c/c++语言开发共享C – fopen()不起作用(返回空指针)

为什么fopen()返回一个空指针?

我试图在cont_br和cont_lan中的BRIDGE之后和局域网(分别为4和5)之后保存参数,但fopen()不起作用…

#include  #include  #include  #include  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: %dn", cont_br); } result = strtok(NULL, delims); if (result == "LAN") { result = strtok(NULL, delims); cont_lan = atoi(result); printf("Number of Lan: %dn", cont_lan); } break; // } } printf("Error: can't open the file! errno: %dn", errno); fclose(file_stream); } int main() { char file[] = "Config.txt"; read_file(file); return 0; } 

这是Config.txt文件:

 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 

    每当fopen失败,然后打印错误号(错误号)。

     #include  

    您应该包含标准errno.h并在代码中打印error值。 然后查看错误代码并找到原因。

     #include  #include  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"); } 

    这样,如果fopen失败,那么它将设置错误号。 您可以在fopen中找到这些错误编号列表。

      以上就是c/c++开发分享C – fopen()不起作用(返回空指针)相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/522899.html

      (0)
      上一篇 2020年12月11日
      下一篇 2020年12月11日

      精彩推荐