从用户输入打开文件的 C 语言 Cat 程序

C Language Cat Program that Opens File from User Input

基本上这个程序试图实现一个简单的 C 版本的 UNIX cat 命令。它只会显示一个文件,如果正确完成,它应该能够在命令行上执行,并带有一个由需要显示的名称组成的命令行参数。我试图将其作为参考的一些问题是 "How to continuously write to a file with user input? C language"、"Create File From User Input" 和 "Fully opening a file in c language"。然而,这些对我没有太大帮助,因为一个想在用光标选择文件时打开文件,另一个是用另一种语言,最后一个有点难以理解,因为我不在那个水平然而。下面是我到目前为止的代码,如果你们都能给我任何建议,我将不胜感激!

#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 30

int main (int argc, char** argv)
{
    File *stream;
    char filename[MAX_LEN];

    printf("File Name: ");
    scanf("%s", filename);
    stream = fopen(filename, "r");

    while(1)
    {
        fgets(stream);
        if(!feof(stream))
        {
            printf("%s", "The file you entered could not be opened\n");
            break;
        }
    }
    printf("To continue press a key...\n");
    getchar();
    fclose(stream);
    return 0;
}

如果您的目标是重新编写 Linux 下的 cat 函数,此代码使用 Linux.

下的打开、关闭和读取系统调用来满足您的目的
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

#define BUFFER_SIZE 50

int main(int argc, char **argv)
{
  int   file;
  char  buffer[BUFFER_SIZE];
  int   read_size;

  if (argc < 2)
    {
      fprintf(stderr, "Error: usage: ./cat filename\n");
      return (-1);
    }
  file = open(argv[1], O_RDONLY);
  if (file == -1)
    {
      fprintf(stderr, "Error: %s: file not found\n", argv[1]);
      return (-1);
    }
  while ((read_size = read(file, buffer, BUFFER_SIZE)) > 0)
    write(1, &buffer, read_size);

  close(file);
  return (0);
}

在这段代码中,您可以看到错误检查是通过验证系统调用不会 return -1(在 linux 下,系统调用通常 return -1 在错误的情况下)。

希望对您有所帮助