这是一个非常简单的问题和我犯的错误,但是谁能解释一下如何使用 sprintf 添加到 argv 值?
在命令行上,我有一个文件名 data.new.txt (但在我的场景中我不知道该文件的名称)如何写入名为 data.new 的新文件。输出.txt
我不想创建具有不同名称的新文件或更新新文件,因为该程序将输出大约 100 多个文件,这就是规范。
int main(int argc, char * argv[]){
char buffer[100];
sprintf(buffer, "%s.decoded", argv[1]);
printf("%s\n", buffer);
}
干杯!
最佳答案
这里有一个 C99(它使用 snprintf()
)程序供您使用。玩得开心!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *buildname(const char *old, const char *newpart) {
char *dot;
char *buf = NULL;
dot = strrchr(old, '.');
if (dot) {
size_t len;
len = snprintf(NULL, 0, "%.*s%s.%s",
(int)(dot - old) + 1, old, newpart, dot + 1);
buf = malloc(len + 1);
if (buf) {
snprintf(buf, len + 1, "%.*s%s.%s",
(int)(dot - old) + 1, old, newpart, dot + 1);
}
}
return buf;
}
int main(void) {
char *p, *q;
q = "data.new.txt";
p = buildname(q, "output");
if (p) printf("%s ==> %s\n", q, p);
else printf("%s ==> (no dots)\n", q);
free(p);
q = "rrrrrrrrrrrr";
p = buildname(q, "aaa");
if (p) printf("%s ==> %s\n", q, p);
else printf("%s ==> (no dots)\n", q);
free(p);
q = "a.b.c.d.e.f.g.h.i.j.k.l";
p = buildname(q, "Q.Q");
if (p) printf("%s ==> %s\n", q, p);
else printf("%s ==> (no dots)\n", q);
free(p);
return 0;
}
关于c - sprintf() 与 argv 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23045916/