【问题标题】:C program is claiming file is not there, but it is?C程序声称文件不存在,但它存在吗?
【发布时间】:2013-12-11 04:42:33
【问题描述】:

所以我有这个代码:

#include <stdio.h>
#include <stdlib.h>
#define MASK 0x07FF
#define TABLE_SEZE 32
#define LITTLE_SIZE 8
#define SIZE 256
#define DEBUG 1

int main() {


    unsigned v_addr = 0;

    FILE *inFilePtr = NULL;
    FILE *outfilePtr = NULL;
    char inFileName[SIZE];
    char outfileName[SIZE];

    printf("Enter the name of the file we are working with!.\n");
    fgets(inFileName, sizeof(inFileName), stdin);

    //open 'er up
    inFilePtr = fopen(inFileName, "r");
    outfilePtr = fopen(outfileName, "w");

    if (inFilePtr == NULL || outfilePtr == NULL){

        printf("Could not open the file.\n");
        exit(1);

    }//end of if

}//end main

我想让它读取一个文件,但它一直说文件不存在。

问题是,文件在当前目录中。怎么回事?

【问题讨论】:

  • 您要读取的文件在哪里?它应该在应用程序路径中。
  • 你在哪里设置outfileName?您怎么知道错误是什么,无论实际错误如何,您都会打印相同的消息。使用例如strerror 获取实际错误。哦,你甚至不知道 哪个 fopen 失败了,至少有一个失败了。
  • 当您使用它时,我认为getcwd() 可能会告诉您一些信息。
  • 与文件在同一目录下。

标签: c file input io


【解决方案1】:

你可以改变

fgets (inFileName, sizeof(inFileName), stdin);

进入

scanf ("%[^\n]s", inFileName);

它会完美运行!

【讨论】:

  • 此更改将buffer overflow exploit 引入程序。如果有人键入的字符多于inFileName 中的字符数,则原始代码是安全的,但您建议的代码会破坏堆栈。
【解决方案2】:

请注意,fgets() 通常会返回一个包含 \n 的字符串,因此如果有的话,您需要将其删除。

例如

char* p = strchr(inFileName, '\n');
if ( NULL != p ) 
{
  *p = '\0'; 
}

您还需要将 outFileName 设置为某个值

例如

strcpy( outFileName, "_" );
strcat( outFileName, inFileName );

【讨论】:

  • 我想赞成这个答案,但fgets 并不总是在行尾放置\n - 例如,如果文件的最后一行没有以尾随换行符结尾,或者如果该行比提供的空间长,它就会停止。 (另外,当你在 () 或 [] 的内部放置空格时,你会让耶稣宝宝哭泣。)
  • @Zack 你当然是对的,我已经修改了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-11
  • 1970-01-01
相关资源
最近更新 更多