dqhdz04240 2019-05-28 17:57 采纳率: 0%
浏览 276
已采纳

为什么fopen与x模式给我“无法打开流:没有这样的文件或目录”

I want to use mode x because as I can see from php.net that if the file exists it gives and error and also return false, and if not it creates it (also the directory's).

This is the script. It is located in www.ex.com/s/index.php

$urlParts = "/img/logo.png";
$fp = fopen( __DIR__ . $urlParts, "x" );

This should create logo.png (and also create the directory /img/) if it does not exist...but it is not working like this.

Anyone can help? Thanks!

  • 写回答

1条回答 默认 最新

  • duane2364 2019-05-28 20:20
    关注
    fopen("/img/logo.png","x");
    

    It will not create the img directory in any case. If the directory does not exist, then it will always throw this warning.

    Warning: fopen(/img/logo.png): failed to open stream: No such file or directory

    fopen("logo.png","x");
    

    If logo.png does not already exist, then it will create it without any warning. If logo.png already exists, then it will always throw this warning.

    Warning: fopen(logo.png): failed to open stream: No such file or directory

    fopen("","x") is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. Now let me help you understand why it happens.

    In POSIX, The O_CREAT flag causes a file to be created if it doesn't already exist. If you include the O_CREAT flag, you must also pass a third argument to open to designate the permissions. If you want to avoid writing over an existing file, use the combination O_CREAT | O_EXCL. This combination returns an error if the file already exists.

    C program using POSIX

    #include <fcntl.h>
    #include <sys/stat.h>
    int open(const char *path, int oflag, ...);
    

    Conclusion: So we will use the "x" mode only when we want to avoid writing over an existing file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分