简体   繁体   English

如何使用命令行输入文件在 linux 上运行 C 代码?

[英]How do I run C code on linux with input file from command line?

I'm trying to do some simple tasks in C and run them from the command line in Linux.我正在尝试在 C 中执行一些简单的任务,并从 Linux 中的命令行运行它们。 I'm having some problems with both C and running the code from the command line with a given filename given as a parameter.我在 C 和使用给定文件名作为参数的命令行运行代码时遇到了一些问题。 I've never written code in C before.我以前从未在 C 中编写过代码。

Remove the even numbers from a file.从文件中删除偶数。 The file name is transferred to the program as a parameter in the command line.文件名作为命令行中的参数传递给程序。 The program changes this file.程序更改此文件。

How do I do these?我该怎么做?

  • read from a file and write the results over the same file从文件中读取并将结果写入同一个文件
  • read numbers and not digits from the file (ex: I need to be able to read "22" as a single input, not two separate chars containing "2")从文件中读取数字而不是数字(例如:我需要能够将“22”作为单个输入读取,而不是包含“2”的两个单独的字符)
  • give the filename through a parameter in Linux.通过 Linux 中的参数给出文件名。 (ex: ./main.c file.txt) (例如:./main.c 文件.txt)

my attempt at writing the c code:我尝试编写 c 代码:

#include <stdio.h>
int main ()
{
    FILE *f = fopen ("arr.txt", "r");
    char c = getc (f);
    int count = 0;
    int arr[20];
    while (c != EOF)
    {
        if(c % 2 != 0){
            arr[count] = c;
            count = count + 1;
        }
        c = getc (f);
    }


    for (int i=0; i<count; i++){
            putchar(arr[i]);
    }
    fclose (f);
    getchar ();
    return 0;
} 

I'd do that like this (removing extra declarations => micro optimizations)我会这样做(删除额外的声明=>微优化)

  /**
   * Check if file is avaiable.
   */ 
  if (f == NULL)
  {
    printf("File is not available \n");
  }
  else
  {
    
    /**
     * Populate array with even numbers.
     */ 
    while ((ch = fgetc(f)) != EOF)
        ch % 2 != 0 ? push(arr, ch); : continue;

    /**
     * Write to file those numbers.
     */ 
    for (int i = 0; i < 20; i++)
        fprintf(f, "%s", arr[i]);
  }

Push implementation:推送实现:

void push(int el, int **arr)
{
    int *arr_temp = *arr;

    *arr = NULL;
    *arr = (int*) malloc(sizeof(int)*(n - 1));

    (*arr)[0] = el;
    for(int i = 0; i < (int)n - 1; i++)
    {
        (*arr)[i + 1] = arr_temp[i];
    }
}

In order to write to the same file, without closing and opening it, you should provide both methods, w+ (writing and reading), and this method will clear it's content.为了写入同一个文件,而不是关闭和打开它,你应该提供两个方法,w+(写入和读取),这个方法会清除它的内容。

So, change the line where you open the file, for this.因此,为此更改打开文件的行。

FILE *f = fopen ("arr.txt", "w+");

You should look for ways of implementing dynamic arrays (pointers and memory management).您应该寻找实现动态 arrays(指针和 memory 管理)的方法。

With this example you could simply go ahead and write yourself, inside the main loop, a temporary variable that stores a sequence of numbers, and stack those values在这个例子中,你可以简单地提前 go 并在主循环中自己编写一个存储数字序列的临时变量,并将这些值堆叠起来

Something like this (pseudocode, have fun:)):像这样的东西(伪代码,玩得开心:)):

DELIMITER one of (',' | '|' | '.' | etc);

char[] temp;
if(ch not DELIMITER)
  push ch on temp;
else
  push temp to arr and clear it's content;

Hope this was useful.希望这很有用。

Here's a complete program which meets your requirements:这是一个满足您要求的完整程序:

  • write the results over the same file - It keeps a read and write position in the file and copies characters towards the file beginning in case numbers have been removed;将结果写入同一个文件- 它在文件中保持读写 position 并在删除数字的情况下将字符复制到文件开头; at the end, the now shorter file has to be truncated.最后,现在更短的文件必须被截断。 (Note that with large files, it will be more efficient to write to a second file.) (请注意,对于大文件,写入第二个文件会更有效率。)
  • read numbers and not digits from the file - It is not necessary to read whole numbers, it suffices to store the write start position of a number (this can be done at every non-digit) and the parity of the last digit.从文件中读取数字而不是数字- 不必读取整数,只需存储数字的写入开始 position(这可以在每个非数字处完成)和最后一位的奇偶校验。
  • give the filename through a parameter - If you define int main(int argc, char *argv[]) , the first parameter is in argv[1] if argc is at least 2.通过参数给出文件名- 如果定义int main(int argc, char *argv[]) ,如果argc至少为 2,则第一个参数位于argv[1]中。
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    if (argc < 2) return 1;   // no argument given
    FILE *f = fopen(argv[1], "rb+");
    if (!f) return 1; // if fopen failed
    // read, write and number position
    long rpos = 0, wpos = 0, npos = 0;
    int even = 0, c;  // int to hold EOF
    while (c = getc(f), c != EOF)
    {
        if (isdigit(c)) even = c%2 == 0;
        else
        {
            if (even) wpos = npos, even = 0;
            npos = wpos+1;    // next may be number
        }
        fseek(f, wpos++, SEEK_SET);
        putc(c, f);
        fseek(f, ++rpos, SEEK_SET);
    }
    ftruncate(fileno(f), wpos); // shorten the file
}

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

相关问题 如何从Linux命令行接受C语言中的标准输入 - How to Accept Standard Input in C from the Linux Command Line 如何使用 .txt 文件作为命令行输入,使其内容作为 C 中的命令行输入读取? - How do I use a .txt file as a command line input in such a way that its contents are read as command line input in C? 如何从命令行运行Eclipse IDE for C / C ++(我已经安装了它) - How do you run Eclipse IDE for C/C++ from the command line (I already installed it) linux命令行在ac文件中 - linux command line in a c file 如何使用C命令行中作为参数传入的文本文件? - How do I use a text file passed in as an argument from the command line in C? 如何从Linux上的Java代码调用C函数 - How do I call C functions from Java code on Linux 使用C在Linux上记录命令行输入和输出 - Recording command line input and output on linux with C linux-如何在C中使用execlp函数运行带有参数的任何命令 - linux- How I do run to any command with parameter with execlp function in C 如何在 AWS EC2 Linux 实例上运行编译和运行 c 文件? - How do I run compile and run a c file on an AWS EC2 Linux Instance? 从命令行从 C 文件中读取输入测试用例 - reading input testcases from a file in C from command line
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM