简体   繁体   English

从命令行参数打开文本文件?

[英]Opening a text file from command line argument?

I have two C files, one is the function definitions file titled " function.c " and the other is the main file titled " main.c ". I have two C files, one is the function definitions file titled " function.c " and the other is the main file titled " main.c ". I am trying to open a text file that is entered by the user as a command-line argument, like below.我正在尝试打开用户作为命令行参数输入的文本文件,如下所示。

./program file.txt

The program then uses "file.txt".然后程序使用“file.txt”。 My main.c code is below:我的main.c代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *readFile(char *filename);

int main(int arg_count, char *arg[]) {

  FILE *fptr = fopen(arg[1] ,"r");

  if(fptr == NULL) {
    printf("Error! opening file");
    exit(1);
  }
  readFile(arg[1]);

  return 0;
}

The main function calls the function within the other c file called "readFile," in "function.c," which is below: The main function calls the function within the other c file called "readFile," in "function.c," which is below:

char *readFile(char *filename) {

fgets(arg[1], sizeof(arg[1]), stdin);

rest of code rest 代码

  return 0;
}

What I want to do with the file, will be written inside of function.c (within the readFile function).我想对文件做什么,将写在function.c内(在 readFile 函数内)。 When I tried compiling it, it gave me an error saying "error: 'arg' undeclared," but when I try to declare it, it gives me another error.当我尝试编译它时,它给了我一个错误说“错误:'arg'未声明”,但是当我尝试声明它时,它给了我另一个错误。 Note that I compile both files together, along with a header file containing the function prototype.请注意,我将这两个文件与包含 function 原型的 header 文件一起编译。 How do I make it so that what is entered from the command line, carries over into the function.c file, so I can use that file?如何使从命令行输入的内容转移到function.c文件中,以便我可以使用该文件?

Arguments to a function only exist within the scope of that function. Arguments 到 function 只存在于 scope 的 ZC1C425268E68385D1AB5074C 中。 char *arg[] does not exist in the scope of the function readFile , even if both functions are in the same source file. char *arg[]不存在于 function readFile的 scope 中,即使这两个函数都在同一个源文件中。

readFile gets a pointer to arg[1] in the argument called filename ; readFile在名为filename的参数中获取指向arg[1]的指针; use that instead in readFile .readFile中使用它。

the following proposed code::以下建议的代码:

  1. cleanly compiles干净地编译
  2. performs the desired functionality执行所需的功能
  3. properly checks for errors (except for call to fgets() )正确检查错误(调用fgets()除外)
  4. documents why each header file is included记录为什么包含每个 header 文件
  5. properly verifies existence of expected command line parameter正确验证预期命令行参数的存在
  6. makes use of dynamic memory for passing string back to caller利用动态 memory 将字符串传回给调用者
  7. cleans up after itself (fclose() and free())自行清理(fclose() 和 free())
  8. uses a 'include' guard to prevent multiple include of the header file使用“包含”保护来防止 header 文件的多次包含
  9. inserts any error messages into stderr to inform the user of any problems将任何错误消息插入到stderr以通知用户任何问题
  10. uses a #define to give the 'magic' number (20) a meaningful name使用#define为“神奇”数字 (20) 赋予有意义的名称

and now, the proposed code:现在,建议的代码:

// myHeader.h
#ifndef MY_HEADER_H
#define MY_HEADER_H

char *readFile(char *filename);   

#endif  // MY_HEADER_H


// main.c
#include <stdio.h>    // fprintf()
#include <stdlib.h>   // exit(), EXIT_FAILURE, free()
#include "myHeader.h"


int main(int arg_count, char *arg[]) 
{
    if( arg_count <= 1 )
    {
        fprintf( stderr, "USAGE: %s inputFileName\n", arg[0] );
        exit( EXIT_FAILURE );
    }
    
    // implied else, command line parameter was entered by user
        

    char *buffer = readFile(arg[1]);
    
    printf( "%s]n", buffer );
    
    free( buffer );

  return 0;
}


// function.c
#include <stdio.h>   // fopen(), fclose(), perror(), fgets()
#include <stdlib.h>  // exit(), EXIT_FAILURE, malloc()
#include "myHeader.h"

#define MAX_BUF_LEN 20

char *readFile( char *filename ) 
{
    FILE *fptr = fopen( filename , "r" );

    if( fptr == NULL ) 
    {
        perror( "fopen failed" );
        exit( EXIT_FAILURE );
    }
    
    //implied else, fopen successful
    
    // read first line from file
    char *buffer = malloc( MAX_BUF_LEN );
    if( buffer == NULL )
    {
        perror( "malloc failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful
    
    fgets( buffer, sizeof(buffer), fptr );

    fclose( fptr );
    
    return buffer;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM