【问题标题】:Why does my program only read the file name when a double file extension is given in C?为什么我的程序在 C 中给出双文件扩展名时只读取文件名?
【发布时间】:2021-10-02 21:24:15
【问题描述】:
#include<stdio.h>                    //standard input output library
#include<stdlib.h>

void main()
{
    FILE  *fp ;                      //fp is the file pointer
    char  ch ;                      //a variable to print contents of the file
    fp = fopen ( "text.txt", "r" ) ;//Normal file name with extension
    while ( 1 )
    {
    ch = fgetc(fp) ;
    if (ch == EOF)                     //if program reaches, EOF, it stops
        break ;
    printf ( "%c", ch);
    }
    fclose ( fp );
}

上面的程序没有读取我的文件,但是当我如下图替换文件名时,它可以工作。

fp = fopen("text.txt.txt", "r") ;//双文件扩展名

为什么 text.txt 不起作用,而 text.txt.txt 起作用?

【问题讨论】:

  • 可能是因为文件“text.txt.txt”存在而“text.txt”不在工作目录中?
  • 无关:如果您要制作有效的程序,请测试您命令该程序执行的操作是否确实有效。 fp = fopen ( "text.txt", "r" ); 可能导致 fp == NULL 你知道的。所有这些。测试测试测试。
  • main 返回int,而不是void。 fgetc 返回int,而不是char,以便可以将值EOF 与任何有效的字符值区分开来。

标签: c file file-handling


【解决方案1】:

这肯定意味着您的文件实际上命名为text.txt.txt。

我推测您的文件浏览器被配置为隐藏文件扩展名:如果文件名为 text.txt,那么您的文件浏览器可能只会显示 text,并且由于它被命名为 text.txt.txt,因此您的文件浏览器会显示text.txt。 (如果我没记错的话,在所有最新版本的 Windows 中,此配置是 Windows 资源管理器中的默认配置,所以我猜这就是您正在使用的配置;但如果有其他文件浏览器可以以这种方式配置。)

【讨论】:

  • 我非常惊讶这种危险的行为仍然是 Windows 的默认设置。
猜你喜欢
  • 2016-03-24
  • 2020-07-09
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
  • 2021-08-29
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多