C语言 如何在字符串末尾添加一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7920793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a character at end of string
提问by Saifur Rahman Mohsin
I have a file copy program that takes from one file and pastes in another file pointer. But, instead of getting targetname from user input i'd like to just add a '1' at the end of the input filename and save. So, I tried something like this...
我有一个文件复制程序,它从一个文件中获取并粘贴到另一个文件指针中。但是,我不想从用户输入中获取目标名称,而是在输入文件名的末尾添加一个“1”并保存。所以,我尝试了这样的事情......
.... header & inits ....
fp=fopen(argv[1],"r");
fq=fopen(argv[1].'1',"w");
.... file copy code ....
Yeah it seems stupid but I'm a beginner and need some help, do respond soon. Thanks :D
是的,这看起来很愚蠢,但我是初学者,需要一些帮助,请尽快回复。感谢:D
P.S. Want it in pure C. I believe the dot operator can work in C++.. or atleast i think.. hmm
PS 希望它在纯 C 中。我相信点运算符可以在 C++ 中工作......或者至少我认为......嗯
One more thing, i'm already aware of strcat function.. If i use it, then i'll have to define the size in the array... hmm. is there no way to do it like fopen(argv[1]+"extra","w")
还有一件事,我已经知道 strcat 函数......如果我使用它,那么我将不得不在数组中定义大小......嗯。有没有办法像 fopen(argv[1]+"extra","w")
回答by BLUEPIXY
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* stradd(const char* a, const char* b){
size_t len = strlen(a) + strlen(b);
char *ret = (char*)malloc(len * sizeof(char) + 1);
*ret = '#include <string.h>
char alpha[14] = "something";
strcat(alpha, " bla"); // "something bla"
printf("%s\n", alpha);
';
return strcat(strcat(ret, a) ,b);
}
int main(int argc, char *argv[]){
char *str = stradd(argv[1], "extra");
printf("%s\n", str);
free(str);
return 0;
}
回答by Morten Kristensen
回答by Dennis
回答by James Matta
Unfortunately . would not work in c++.
很遗憾 。在 C++ 中不起作用。
A somewhat inelegant but effective method might be to do the following.
一种不太优雅但有效的方法可能是执行以下操作。
##代码##回答by Turcogj
In C to concatenate a string use strcat(str2, str1)
在 C 中连接字符串使用 strcat(str2, str1)
strcat(argv[1],"1")will concatenate the strings. Also, single quotes generate literal characters while double quotes generate literal strings. The difference is the null terminator.
strcat(argv[1],"1")将连接字符串。此外,单引号生成文字字符,而双引号生成文字字符串。不同之处在于空终止符。

