我试图在C中执行一些简单的任务,并在Linux中的命令行中运行它们。我在C和从命令行运行代码时都遇到了一些问题,给定的文件名是参数。我以前从未用C写过代码。
从文件中删除偶数。文件名作为命令行中的参数传递给程序。程序将更改此文件。
我该怎么做?
我编写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;
} 发布于 2021-04-25 22:30:28
这里有一个完整的程序,可以满足您的要求:
int main(int argc, char *argv[]),第一个参数在argv[1]中,如果argc至少为2。#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
}发布于 2021-04-25 21:08:11
我会这样做(删除额外的声明,=>微优化)
/**
* 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]);
}推动执行:
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];
}
}为了写入同一个文件,而不需要关闭和打开它,您应该提供两个方法,w+ (写和读),这个方法将清除它的内容。
因此,请更改打开文件的行。
FILE *f = fopen ("arr.txt", "w+");您应该寻找实现动态数组的方法(指针和内存管理)。
在本例中,您可以直接在主循环中编写一个临时变量,用于存储数字序列,并将这些值进行堆栈()。
类似的东西(伪代码,玩得开心:):
DELIMITER one of (',' | '|' | '.' | etc);
char[] temp;
if(ch not DELIMITER)
push ch on temp;
else
push temp to arr and clear it's content;希望这是有用的。
https://stackoverflow.com/questions/67257598
复制相似问题