我需要创建一个程序来读取带有“.deck”扩展名的文件。也就是说,程序参数应该是-d1 <name>.deck
. 该-d1
字符串必须始终写入和.deck
扩展是强制性的,在<name>
可以是任何给定的字符串与任何给定长度。该.deck
文件基本上是一个带有扑克牌组的文本文件。谢谢 :)
这可能就是你要找的。
当前,以下程序循环遍历所有命令行参数并搜索-d1
标志。找到后,它会确保存在下一个参数,即在尝试打开它之前,它是一个带有 .deck 扩展名的字符串。
请注意,此程序不会处理多个文件。您将需要实现某种链接列表或数组来存储多个fds
或字符串。
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
static const char *FLAG = "-d1";
static const char *EXTENSION = ".deck";
int is_deck_file(char const *string)
{
int length = strlen(string);
if (length < 6)
return 0;
if (strcmp(string + (length - 5), EXTENSION) == 0)
return 1;
return 0;
}
int main(int argc, char const *argv[])
{
int fd = -2;
for (unsigned int i = 0; i < argc; i++) {
if (strcmp(argv[i], FLAG) == 0) {
if (i + 1 < argc && is_deck_file(argv[i + 1])) {
i++;
fd = open(argv[i], O_RDONLY);
} else {
dprintf(2, "Error: %s flag must be followed by a filepath.\n", FLAG);
}
}
}
if (fd == -2)
dprintf(2, "No file was provided.\n");
else if (fd == -1)
dprintf(2, "Unable to open file.\n");
else
dprintf(1, "File provided, with right extension!\n");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句