gpt4 book ai didi

使用命令行参数在 C 程序中创建多个文件

转载 作者:太空宇宙 更新时间:2023-11-04 01:58:06 25 4
gpt4 key购买 nike

我正在尝试创建一个 C 程序,其中包含一个包含 50 行的 text.txt 文件。这个text.txt文件应该分成5个文件,比如text_part1.txt、text_part2.txt等等。 text.txt 文件中的 50 行应平均复制为 5 个文件中每行 10 行。

所有这些都必须通过使用命令行参数来完成。我是 C 的初学者,刚刚开始编写代码。我不知道如何使用命令行参数。

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

int main()
{
FILE *ptr_readfile;
FILE *ptr_writefile;
char line [100];
char fileoutputname[10];
int filecounter=1, linecounter=1;

ptr_readfile = fopen("C:/home/dir/sample_pg/data/text.txt","r");
if (!ptr_readfile)
return 1;

sprintf(fileoutputname, "file_part%d", filecounter);
ptr_writefile = fopen(fileoutputname, "w");

while (fgets(line, sizeof line, ptr_readfile)!=NULL)
{
if (linecounter == 5)
{
fclose(ptr_writefile);
linecounter = 1;
filecounter++;
sprintf(fileoutputname, "file_part%d", filecounter);
ptr_writefile = fopen(fileoutputname, "w");
if (!ptr_writefile)
return 1;
}
fprintf(ptr_writefile,"%s\n", line);
linecounter++;
}
fclose(ptr_readfile);
return 0;
}

最佳答案

要获取程序的参数,您需要使用参数计数(通常命名为 argc)和参数数组(通常命名为 argv)定义 main 函数), 所以像

int main(int argc, char**argv) {
for (int ix=1; ix<argc; ix++) {
FILE* fil = fopen(argv[ix], "r");
if (!fil) { perror(argv[ix]); exit(EXIT_FAILURE); };

当您将其(与一些其他需要的代码)编译成可执行文件 foo.exe 并在终端上运行 foo.exe a b c 时,argc 是 4 而你有

      argc == 4 &&
strcmp(argv[0], "foo.exe") == 0 &&
strcmp(argv[1], "a") == 0 &&
strcmp(argv[2], "b") == 0 &&
strcmp(argv[3], "c") == 0 &&
argv[4] == NULL

请注意,在像 fopen 这样的函数失败时调用 perror 是一个好习惯

顺便说一句,您忘记在程序中调用fclose。您还可以了解有关 fflush 的更多信息。而且你应该更喜欢 snprintf 而不是 sprintf 以避免 buffer overflows .了解更多,并且非常害怕,undefined behavior .

请养成编译所有警告和调试信息的习惯(例如 gcc -Wall -Wextra -g 如果使用 GCC ....)然后学习如何使用调试器。

阅读perror(3) , fopen(3) , fclose(3) , fflush(3) , snprintf(3)养成阅读 documentation 的习惯您要使用的每个功能。

另见 csplit ;您可能会通过研究 free software 的源代码获得一些灵感。包裹coreutils在 Linux 上实现它。

关于使用命令行参数在 C 程序中创建多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31041075/

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