【问题标题】:File creation through fopen works fine on Linux but not on Windows (MS VS 2010)通过 fopen 创建文件在 Linux 上运行良好,但在 Windows 上运行良好(MS VS 2010)
【发布时间】:2012-04-18 11:06:01
【问题描述】:

您好,我正在尝试在 Microsoft Visual Studio Ultimate 2010 中执行由以下代码生成的 .exe 文件,但没有看到正在创建的文件。

这段代码在使用 GCC 的 Linux 中编译和执行时运行良好。

重复一遍,我可以使用在 Linux 中创建的文件!但在 Windows 中,.exe 程序无法为用户在命令提示符下输入的名称创建文件。

有人可以让我知道我在编译器方面出了什么问题吗?

衷心感谢

// filename.cpp : Defines the entry point for the console application.

    #include "stdafx.h"        //Please comment if code is to be executed in GCC
    #include <stdio.h>
    #include <stdlib.h>
    #include <memory.h>

    int main()
    {
        FILE *pFile;
        char cNotes_buffer[100];
        memset(cNotes_buffer,0,100);
        printf("Please enter name of the LOG file - with tag MAX 100 characters!! \n");
        if( fgets (cNotes_buffer , 100 , stdin) != NULL )
            {
            fclose (stdin);
        }

        printf("name of file %s \n", cNotes_buffer);
        if ( ( pFile = fopen(cNotes_buffer,"a+") ) == NULL )
        {
            printf("ERROR OPENING FILE FOR LOGGING \n");
            exit(0);
        }
        return 0;
    }

【问题讨论】:

  • 尝试perror()(而不是printf())获取错误消息。通过perror(),您还可以获得有关错误的更多信息。
  • @pmg AFAIK 窗口没有perror()。这是GetLastError()
  • @RedX:除非使用的 Windows 编译器不符合 ANSI C89 / ISO C90,否则 Windows 有perror()
  • 因为他使用的是visual studio,所以他可以使用perror(),但值得注意的是GetLastError有时可以提供更多细节
  • @pmg Visual Studio 编译器不是 C 编译器。它是一个具有 C 特性的 C++ 编译器。但很高兴知道它有perror()。 [MSDN]!(msdn.microsoft.com/de-de/library/yeby3zcb%28v=vs.100%29.aspx) 表示perror() 就够了

标签: c windows linux visual-studio-2010 gcc


【解决方案1】:

您很可能会在输入文件名后按 ENTER。所以\n 也进入了cNotes_buffer。现在您尝试创建一个以该缓冲区为文件名的文件。而且我认为您不能在其中创建带有\n 的文件名。

如果您按下了返回键,请执行类似操作

cNotes_buffer[strlen(cNotes_buffer)-1]=0;

编辑:换行符可以出现在 linux 中的 filenames 中,但 Windows 中则不然

【讨论】:

  • 有可能他的文件是在 linux 的末尾使用换行符创建的。这在 Windows 上是不允许的
【解决方案2】:

尝试fclose(pFile)。未能关闭文件会导致奇怪的行为。

【讨论】:

  • 你好 @Pavan Manjunath,@pmg,@CodeChords 人感谢您的反馈..我错过了 Pavan 强调的一些非常重要的东西,所以我错过了在 \n 中添加的那句话到文件名......而且这在Linux中工作正常但是当目录内容的列表完成时,我得到的文件名附加了?至少在 Linux 上。谢谢
猜你喜欢
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多