[英]How to use command line argument to input data and convert data into uppercase
[英]Trying to use command line ls -l argument as scanf input
我正在尝试通过ls -l输出来分析文件的权限和大小。 但是,似乎scanf()函数在空格之后不包含任何内容。 是否有任何技巧或解决方法? 我想坚持使用scanf,但是如果不可能的话,我欢迎您提出建议。 当我运行下面的程序并打印test2时,只会存储“总计”。
<#include stdio.h>
int main(int argc, char **argv){
char test[200];
char test2[200];
scanf("%c\n", test);
for(int i = 0; i < 9 ; i++){
if(test[i] != '\n'){
test2[i] = test[i];
}
}
for (int i = 0; i < 9; i++){
printf("%c\n", test2[i]);
}
return 0;
}
谢谢。 还可以通过仅使用ls -l来检查某物是文件还是目录吗?
但是,似乎scanf()函数在空格之后不包含任何内容。 ...
scanf("%c\\n", test);
不是scanf()
,它是使用的格式。 scanf("%c\\n", test);
将1个char
扫描到test
(test不一定是空字符终止),然后扫描并扔掉任何空白。 它将继续这样做,直到找到非空白。
您更可能需要scanf(" %199[^\\n]", test); fgetc(stdin);
scanf(" %199[^\\n]", test); fgetc(stdin);
这将1)扫描并丢弃空白,2)扫描多达199个非'\\n'
。 3)当检测到已满,EOF或'\\n'
时停止。 然后扫描下一个字符并扔掉。
一般来说。 最好使用fgets()
if (fgets(test, sizeof test, stdin) == NULL) Handle_EOF();
test[strcspn(test, "\n")] = 0; // lop off potential \n.
for (size_t i = 0; test[i]; i++){
printf("%c\n", test[i]);
}
需要明确的是,并不是scanf()
是邪恶的,它只是试图做很多事情(IO和转换)。 最好分开。
大多数scanf()
格式说明符和指令' '
不能区分空格和'\\n'
。 该行的结尾对于您的代码至关重要。 fgets()
寻找一个'\\n'
并将空格与其他char
一样对待。
谢谢。 还可以通过仅使用ls -l来检查某物是文件还是目录吗?
第一行以“ total”开头,可以丢弃。
接下来的每一行(使用fgets()读取每一行)均以“权限”开头
权限的第一个字符表示文件类型:
'd' directory, 'c' character oriented device, 'b' block oriented device, '-' normal file, 'p' for named pipes, 's' for socket, 'D' for interprocess communication between client and server (solarus UNIX only) 'l' symbolic link
您也可以尝试使用格式化的scanf功能,该功能可让您指定所需的输入格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.