c - 从 stdin (C) 获取多个文件的文件大小

标签 c filenames stdin

我正在尝试从 stdin 的 1 行中读取并获取多个文件的总文件大小。如果有 1 个文件,下面的代码可以完美运行,但如果有多个文件,它就会失败,因为它无法区分 1 个文件何时结束和另一个文件何时开始。文件名由空格分隔(例如:echo“file1.txt file2.txt”),有人可以指出我如何单独评估每个文件名大小的正确方向吗?为简洁起见,未包含文件大小函数

int main (int argc, char *argv[])
{
    char tmpstring[1024];
    const char* fileName;
    off_t size;
    char* pos;
    int total = 0;

    //read from stdin
    while (fgets(tmpstring, 1024, stdin)) 
    {
        fileName = tmpstring;
        if ((pos=strchr(fileName, '\n')) != NULL)
            *pos = '\0';


        printf("this is the name: %s\n", fileName); //#DEBUG
        size = filesize(fileName);
        total += size;
    //} #DEBUG

    }


    printf("This is the total: %d\n", total); //#DEBUG
    return -1;

}

最佳答案

如何使用 scanf 代替:

int main() {
    char buffer[1024];
    int total = 0;

    while (scanf("%1023s", buffer) == 1) {
        printf("this is the name: %s\n", buffer);
        total += filesize(buffer);
    }

    printf("This is the total: %d\n", total);
    return 0; // You shouldn't return -1!
}

scanf 首先消耗前导空白,然后读取一系列非空白字符。返回值 1 表示字符串已成功读取(警告:scanf 实际上返回匹配的输入项数;请参阅手册!)。

最大字段宽度说明符(%1023s 中的1023)对于避免 buffer overflow vulnerability 是必需的.如果我省略了它,则可以将超过 1023 个字符的字符串提供给 scanf。需要额外的字符来存储空终止符。

注意:此方法的一个(可能不受欢迎的)副作用是没有必要在一行中输入所有文件名。如果您不想要这种行为,可以修改您的初始方法:

int main(int argc, char *argv[]) {
    char buffer[1024];
    const char* fileName;
    int total = 0;
    char *pos;

    // Read from stdin. You should do some error checking too.
    fgets(buffer, sizeof buffer, stdin);

    // Get rid of the trailing '\n'.
    if ((pos = strchr(buffer, '\n')) != NULL)
        *pos = '\0';

    fileName = strtok(buffer, " ");
    while (fileName) {
        printf("this is the name: %s\n", fileName);
        total += filesize(fileName);
        fileName = strtok(NULL, " ");
    }

    printf("This is the total: %d\n", total);
    return 0;
}

附带说明,您不应该使用 int 来表示文件大小int 在您的机器上很可能只有 32 位,在这种情况下,即使是一些相对较小的文件也可能溢出它。

关于c - 从 stdin (C) 获取多个文件的文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28828166/

相关文章:

c++ - 获取不带扩展名的文件名?

ruby - 如何将 Ruby 的 STDIN 传递给 Open3.popen3 调用的外部程序?

linux - 我想从另一个脚本运行一个脚本,使用相同版本的 perl,并将 IO 重新路由到类似终端的文本框

为 Windows(在 Linux 中)编译带有 GLUT 头文件的 C 程序

c - strlen 函数返回类型 - c 编程

Azure 数据工厂 ADF 数据管道将文件名包含在将数据复制到 SQL 数据库中

Python重命名字符串

node.js - 从nodejs中的stdin读取强制将\r\n转换为\n

c - 在c中使用静态数组存储数据

c - 使用 malloc 分配的字符串 在函数返回后可访问