c - 如何使用 scanf 函数从 ls -l 作为参数的结果中解析两个特定信息?

标签 c scanf ls

someuser:~/repo/a1/part1> /bin/ls -l
total 12
-rw------- 1 someuser student  489 Jan 28 07:30 file.c
-rw------- 1 someuser student  462 Jan 16 12:44 Make
drwx------ 2 someuser student 4096 Jan 28 03:59 test_inputs

以结果中的第二行为例。

-rw-------- 1 someuser 学生 489 Jan 28 07:30 file.c

我想通过 scanf 将权限-rw------- 和文件大小489 解析为另一个函数中的参数> 功能。我该如何实现它?

最佳答案

Use fgets()

读取然后解析它。 @Some programmer dude

“scanf...是必需的”是一个不好的要求。但有时我们的顾客——嗯——有点愚蠢。

using the scanf function

关键是需要解析整行,以便为下一次解析对齐输入。

一个相当简单的方法是使用:

  • "*" 根据说明符进行扫描,但不保存。
  • 查找最后的'\n' 或文件结尾。

scanf() details

// -rw------- 1 someuser student  489 Jan 28 07:30 file.c

char rights[10+1];
unsigned long long size;
int count;
for (;;) {
  char eol = '\n';
  count = scanf("%10s %*d %*s %*s %llu %*s %*d %*d:%*d %*s%c", rights, &size, &eol);
  if (count == EOF) break;
  if (count >= 2 && eol == '\n') {
    printf("Rights:<%s> size:%llu\n", rights, size);
  } else {
    // input ill formed, handle error
    // Perhaps report error, then read and toss, up to the end-of-line
    TBD();
  }
}

关于c - 如何使用 scanf 函数从 ls -l 作为参数的结果中解析两个特定信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54403359/

相关文章:

java - 像链一样左移数组

c - C是强类型的吗?

c - 使用 fscanf 逐行遍历 FILE

regex - ls 和正则表达式 linux

linux - 我可以列出逻辑卷上的文件和目录吗

c - 对齐 ls 中的列

c - 如何在文件系统中找到循环?

c - Netbeans 8.1 C 调试器错误?

c - 为什么 fscanf/scanf 正在更改 Ideone.com 上先前扫描的变量的值?

c - 如何在c中读取由 ":"分隔的两个字符串