C程序无法打开文件 [英] C Program can't open file

查看:613
本文介绍了C程序无法打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一文件夹中有程序proba2.exe和文件text.txt,当我在项目属性中设置命令行参数时,它无法打开文件,但是当我从命令提示符运行程序时,它可以正常工作.

I have program proba2.exe and file text.txt in same folder, when I set command line argument in project properties it can't open file, but when I run program from command prompt it works fine.

/* count.c -- using standard I/O */
#include <stdio.h>

#include <stdlib.h> // ANSI C exit() prototype
int main(int argc, char *argv[])
{
    int ch;         // place to store each character as read
    FILE *fp;       // "file pointer" 
    long count = 0;

    if (argc != 2)
    {
        printf("Usage: %s filename\n", argv[0]);
        exit(1);
    }
    if ((fp = fopen(argv[1], "r")) == NULL)
    {
        printf("Can't open %s\n", argv[1]);
        exit(1);
    }
    while ((ch = getc(fp)) != EOF)
    {
       putc(ch,stdout);  // same as putchar(ch);
       count++;
    }
    fclose(fp);
    printf("File %s has %ld characters\n", argv[1], count);

    return 0;
}

从cmd.exe运行正常 当我在命令参数项目属性窗口中指定完整路径时,也可以正常工作(但会为文件名写完整路径)

It works fine running from cmd.exe Also work fine( but writes full path for a name of file) when I specify full path in command arguments project properties window

推荐答案

从资源管理器启动程序时,请确保正在运行的程序的工作目录与程序文件所在的目录相同.我不确定可以在Windows的哪个位置进行设置,但是我认为这是问题所在.

Make sure that the working directory of the running program is the same in which the program file is stored when you start it from the explorer. I am not sure where this can be set up in Windows, but I think this is the problem..

这篇关于C程序无法打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆