我需要将两个字符阵列组合为C语言的第三个字符阵列



我试图将两个char阵列组合到第三个字符阵列中,让我们查看以下示例:

在此代码中,我已经在AV [1]和AV [2]中获得了值。

仅出于一个值的示例,让AV [1] = AB和AV [2] = Fg

main (char *av[])
{
av[2] = av[1] "/" av[2]
printf ("%s" , av[2]);
}

我期望的是: ab/fg

当我运行代码时,出现错误时说:预期';'在字符串常数之前。我认为这不是问题。


我找到了答案,这里是所有的溶液代码,感谢您的帮助,对不起,如果井井有条,我仍在学习。以下代码实际上执行了CP在Linux终端中所做的工作,它只是CP的重复函数。它可能无法完成CP可以做的所有事情,但它可以完成大多数事情。

#include        <stdio.h>
#include        <unistd.h>
#include        <fcntl.h>
#include    <sys/stat.h>                    /*hearder to use Stat system 
call*/
#define BUFFERSIZE      4096
#define COPYMODE        0644
void oops(char *, char *);
main(int ac, char *av[])/*argument vector*/
{
int     in_fd, out_fd, n_chars;
char    buf[BUFFERSIZE];
if ( ac != 3 ){ /* argument account"ac"*/
    fprintf( stderr, "usage: %s source destinationn", *av);
    exit(1);
}


printf("%s", av[2]);                    /*Test deleat after code works*/

struct stat src, dst;                                       // struct is a 
variable that combies all types into one

stat(av[1], &src);                                      //stat system call
stat(av[2], &dst);                                      //stat system call

if( dst.st_mode & S_IFDIR ){                                    // checks 
 if the second argument int the array is a file or a directory
printf ("n It is a directory n");
printf("%s", av[2]);

strcat(av[2],"/");              /* it concatenates two string or character*/
strcat(av[2],av[1]);                /* It takes two argument, i.e, two strings or character arrays, and stores the resultant concatenated string in the first string specified in the argument.*/
printf("n %s",av[2]);              /* testing if values are the same as 
expected*/
printf("n %s",av[1]);




    }


if ((src.st_dev == dst.st_dev) && (src.st_ino == dst.st_ino)) {                 /* compering the file attribute of an inode number and the id of device*/
printf("n Destination file and source file are same n");                  
}
else {

if ( (in_fd=open(av[1], O_RDONLY)) == -1 )
    oops("Cannot open ", av[1]);
if ( (out_fd=creat( av[2], src.st_mode)) == -1 )                    /* "st_mode" indicates the permissions on the file, tells the modes on a file.*/
    oops( "Cannot creat", av[2]);



while ( (n_chars = read(in_fd , buf, BUFFERSIZE)) > 0 )
    if ( write( out_fd, buf, n_chars ) != n_chars )
        oops("Write error to ", av[2]);
if ( n_chars == -1 )
    oops("Read error from ", av[1]);

if ( close(in_fd) == -1 || close(out_fd) == -1 )
    oops("Error closing files","");
}
}
void oops(char *s1, char *s2)
{
    fprintf(stderr,"Error: %s ", s1);
    perror(s2);
    exit(1);
}

尝试<string.h>

strcat函数

非常基本的示例:

char a[15] = "Hello";
char b[] = "World";
strcat(a, " ");
strcat(a, b);
printf("%s", a);

输出:

你好世界

只需确保目标字符阵列有足够的空间容纳整个串联字符串即可。

如果您要做的就是打印结果,请执行此操作:

printf("%s/%s", av[1], av[2]);

最新更新