如何从 scanf() 语句读取文本文件

问题描述 投票:0回答:1

我有一个基本的 C 程序,它读取名为“inputFile.txt”的文本文件,但我想修改该程序以询问用户文件名,然后读取该文件。我附上了读取文件的程序部分供参考。

int main()
{
    FILE *fileHandle; 
    int numberCount = 0, letterCount = 0, punctCount = 0, otherCount = 0;
    int totalCount = 0;
    fileHandle = fopen("inputFile.txt", "r"); 
    
    if (fileHandle != NULL) //If the file isn't empty, it will begin the while loop.
      { 
        int c;
        while ((c =fgetc(fileHandle)) != EOF ) //Until the end of the file, it will check each character

(我只是包含了 if 和 while 循环条件,以防需要修改)

我尝试扫描并将输入保存到 fileHandle,但它不起作用。我需要对该程序进行更多更改,例如反向打印其内容,但这才是真正减慢我进度的原因,所以我将不胜感激任何帮助。

c file text string.h
1个回答
0
投票

这可以像下面这样完成:

  char fileName[50];

  // get user input for fileName
  scanf("%s", fileName);
  fileHandle = fopen(fileName, "r"); 
© www.soinside.com 2019 - 2023. All rights reserved.