C 中的命令行参数和 ftruncate

标签 c file file-io io truncate

我正在尝试制作一个 C 程序,通过使用 ftruncate 截断或扩展输入文件来将输入文件的大小更改为所需的大小。它还必须使用命令行参数。

例如,以下是有效输入:

./changefilesize data.txt 100

如果data.txt的大小=100,则返回保存文件,如果大于100则截尾,如果小于100,则将文件大小扩展为100。

我在处理输入参数和使用 ftruncate 时遇到问题。我找到的关于 ftruncate 的唯一信息基本上是 man 信息,上面写着:

#include <unistd.h>
int ftruncate(int fildes, off_t length);
int truncate(const char *path, off_t length);

这是我目前所拥有的:

#include <stdio.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
    if ( argc != 2 ) {
        printf("2 inputs expected\n");
    }
    else {
        int length;
        length = atoi (argv[1]);
        FILE *file = fopen(argv[0], "r");
        int ftruncate(int file, off_t length);
        fclose(file);
    }
}

如果我输入 ./changefilesize data.txt 100,我会得到 2 inputs expected 但我不明白为什么。

编辑:根据答案更新代码:

#include <stdio.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
    long length;
    length = atoi (argv[2]);
    FILE *file = fopen(argv[1], "w");
    ftruncate (fileno(file), length);
    fclose(file);
}

最佳答案

argv[0] 指向的字符串表示程序名称,因此您将收到 3 个参数:changefilesizedata.txt100

这里

    FILE *file = fopen(argv[0], "r");
    int ftruncate(int file, off_t length);
    fclose(file);

第二行是原型(prototype)(不是调用ftruncate)改成

    FILE *file = fopen(argv[1], "w"); /* 1 instead of 0 and "w" instead of "r" */
    ftruncate(fileno(file), 100);
    fclose(file);

请注意,使用 ftruncate 文件必须是可写的。

关于C 中的命令行参数和 ftruncate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37743414/

相关文章:

c++ - C函数指针

Python 具有特定文件大小范围的文件数量

python - r+ 和 w+ 模式之间的确切区别是什么?

c - 为什么“while(!feof(file))”总是错误的?

c++ - 为游戏节省大量数据

c - 为什么在 fopen() 中使用无效模式时 gcc 不给出警告或错误?

c - 使用c打印格式

c - 保证 4*ceil(n/3) 有足够的存储空间,其中 n 是一个 int

c - 在同一程序中使用 mmap 和 malloc 分配内存是否安全?

Java 程序从文本文件读取输入并进行相应修改