gpt4 book ai didi

c - 一种采用一个命令行参数并将文件内容输出到标准输出的程序。

转载 作者:行者123 更新时间:2023-11-30 16:38:20 25 4
gpt4 key购买 nike

我被分配了一个要编写的程序,该程序使用文件系统调用来获取命令行参数(假设您传入文本文件地址)并返回所述文件的内容。到目前为止,我已经有了这段代码,但似乎无法弄清楚为什么我的编译器在识别作为参数传递的文本文件以及打印从文件接收到的信息方面给出错误。非常感谢任何形式的帮助/帮助。

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>



int main(int argc, char *argv[]){




int FP;
ssize_t bytes;

char buffer [100];

if(argc == 1){

FP = open(argv[1], O_RDONLY);
printf("Program name is : %s", argv[0])
bytes = read(FP, buffer,sizeof(buffer) -1);
printf("%s", bytes);
close(FP);

}






return 0;


}

最佳答案

以下建议代码:

  1. 合并对问题的评论
  2. 实现所需的功能
  3. 正确检查错误
  4. 记录了包含头文件的原因。一般来说,如果您无法说明为什么要包含头文件,那么就不要包含它。 (然后编译器会告诉您是否确实需要该头文件,以及为什么
  5. 编译时始终启用警告,然后修复这些警告。 (对于gcc,至少使用:-Wall -Wextra -pedantic -Wconversion -std=gnu11)

现在是建议的代码。

#include <stdio.h>   // fopen(), perror(), fgets(), fprintf(), printf(), FILE
#include <stdlib.h> // exit(), EXIT_FAILURE


#define MAX_INPUT_LEN 100

int main(int argc, char *argv[])
{
FILE *fp;
char buffer [ MAX_INPUT_LEN ];

if(argc != 2)
{
fprintf( stderr, "USAGE: %s fileName\n", argv[0] );
exit( EXIT_FAILURE );
}

// implied else, correct number of command line parameters

printf( "Program name is : %s", argv[0] );
printf( "file to read: %s\n", argv[1] );

fp = fopen( argv[1], "r" );
if( NULL == fp )
{
perror( "fopen failed" );
exit( EXIT_FAILURE );
}

// implied else, fopen successful

while( NULL != fgets( buffer, sizeof buffer, fp ) )
{
printf( "%s", buffer );
}

fclose( fp );

return 0;
}

关于c - 一种采用一个命令行参数并将文件内容输出到标准输出的程序。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47519919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com