我尝试过的多种形式之一是
char *text, ebuf[32];
int *num;
strncpy (ebuf,tfp->d_name,strlen(tfp->d_name));
sscanf (ebuf, "%s_%i.txt", text, num);
我最初使用 tfp->d_name 代替 ebuf hack,得到了相同的结果:段错误。我从手册页中了解到,也许 %s 应该是 %4c (文本字符串有 4 个字符 - 但并非总是如此)。无论如何 %4c 或 4%c 没有任何区别。
感谢所有回复的人。您的澄清 - 尤其是 WhozCraig 的“更好的手册页” - 让我走上了正轨。
初始化问题不是我的主要问题,而是 sscanf 的语法。对于我的程序,一旦初始化完成,我真正需要的一行是:
sscanf (tfp->d_name, "%[^_]_%i", &text[0], &num);
最佳答案
您的指针未初始化,因此指向任何一致的内容。
您可以使用 malloc 为它们分配空间,例如:
char *text = malloc(max_len);
int *num = malloc(sizeof(int));
// ....
free(text);
free(num);
如您所见,必须free
释放malloc
内存才能释放分配的内存。
否则,您可以使用一个简单的变量和一个数组来存储您的 c-string
char text[max_len];
int num;
// ...
sscanf (ebuf, "%s_%i.txt", text, &num);
看看这个 SO question了解如何触发“_”作为字符串分隔符。 所以,正如 BLUEPIXY 评论你的那样:
sscanf(ebuf, "%[^_]_%i.", text, &num);
最后一件事,您可以避免 strncpy
和 sscanf
直接到 tfp->d_name
sscanf(tfp->d_name, "%[^_]_%i.", text, &num);
这也避免了由于没有 null 终止的 ebuf
字符串而导致 sscanf
的“爆炸”:您应该使用 strlen(tfp->d_name)+1
作为 strncpy
的第三个参数,将 null 终止符也复制到 ebuf
中。
如strlen Man说:
DESCRIPTION
The strlen() function calculates the length of the string pointed to by s, excluding the terminating null byte ('\0').
强调我的
关于c - 我有一个文件名 ABCD_81018293.txt。我尝试 sscanf 将 ABCD 获取为文本,将数字获取为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39739175/