简体   繁体   English

将一个字符串复制到另一个字符串,直到 C 中的某个字符

[英]Copy one string to another until certain character in C

So, I'm creating a program in c, which works with files.所以,我正在用 c 创建一个程序,它可以处理文件。 I'm trying to get the string that the user typed until certain character.我正在尝试获取用户输入的字符串,直到某个字符。
For example: the user typed test.txt, I would need the other variable to get all the text until the '.', so the other string would be test例如:用户输入 test.txt,我需要另一个变量来获取所有文本,直到 '.',所以另一个字符串将是 test
I used strchr, but it gets the string after the point I need, is there any simple method to get the part before the dot?我使用了strchr,但是它在我需要的点之后获取字符串,是否有任何简单的方法可以获取点之前的部分?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 100

int main()
{
    char nome_arquivo[MAX];
    char conteudo[MAX];
    char *nome_backup;

    printf("Nome do arquivo que deseja realizar BACKUP com a extensao: ");
    fgets(nome_arquivo, MAX, stdin);

    //Sempre cuidar com o \n pois ele pode causar erros.
    strtok(nome_arquivo, "\n");

    FILE *arq = fopen(nome_arquivo, "r");

    rewind(arq);
    printf("\nMensagem dentro do arquivo:\n");

    while (fgets(conteudo, MAX, arq) != NULL)
    {
        printf("%s\n",conteudo);
    }

    nome_backup = strchr(nome_arquivo, '.');

    printf("%s\n", nome_backup);

    //FILE *arqbak = fopen(strcat(,".bak"),"w");

}

UPDATE:更新:

int main()
{
    char nome_arquivo[MAX];
    char conteudo[MAX];
    char *nome_backup;

    printf("Nome do arquivo que deseja realizar BACKUP com a extensao: ");
    fgets(nome_arquivo, MAX, stdin);

    //Sempre cuidar com o \n pois ele pode causar erros.
    strtok(nome_arquivo, "\n");

    FILE *arq = fopen(nome_arquivo, "r");

    rewind(arq);
    printf("\nMensagem dentro do arquivo:\n");

    while (fgets(conteudo, MAX, arq) != NULL)
    {
        printf("%s\n",conteudo);
    }

    nome_backup = strtok(nome_arquivo, '.');

    printf("%s\n", nome_backup);

    //FILE *arqbak = fopen(strcat(,".bak"),"w");

}

The ERROR is: Segmentantion fault (core dumped)错误是: Segmentantion fault (core dumped)

HI you can you extract string upto "."嗨,您可以将字符串提取到“。” and store it in different variable.并将其存储在不同的变量中。

int main() {

//User input array
char nome_arquivo[MAX];
printf("enter the string:");
scanf("%s",&nome_arquivo);

//Required array
char name[MAX];

//copying string upto "."
for(int i=0; i<MAX; i++) 
{
if (nome_arquivo[i]==".")
break;
else
name[i]=nome_arquivo[i]);
}

// now name consists of your required string
}

You are making it very awkward on yourself.你让自己很尴尬。 You are doing a good job in using fgets() to handle the input, but you do not need to tokenize the line of input to separate the filename and extension.您在使用fgets()处理输入方面做得很好,但您不需要标记输入行以分隔文件名和扩展名。 Instead, (and instead of using strchr() ), use strrchr() to locate the last '.'相反,(而不是使用strchr() ),使用strchr() strrchr()来定位最后一个'.' in the input string.在输入字符串中。 That way if you have a filename that is similar to "somefile.version.ext" you can properly separate the filename into the name "somefile.version" and the extension "ext" .这样,如果您有一个类似于"somefile.version.ext"的文件名,您可以将文件名正确地分成名称"somefile.version"和扩展名"ext"

strrchr will provide a pointer to the final '.' strrchr将提供指向最后一个'.'的指针'.' in the input (or NULL if there is no '.' included).在输入中(如果不包含'.' ,则为NULL )。 There you have the address of the array filled by fgets() and you have the address of the final '.'在那里你有由fgets()填充的数组的地址,你有最后一个'.'的地址'.' in that string, all you need to do is subtract the pointer returned by strrchr() and the array filled by fgets() to determined the number of characters to copy.在该字符串中,您需要做的就是减去strrchr()返回的指针和fgets()填充的数组以确定要复制的字符数。 Then a simple call to memcpy is all you need to perform the copy and then nul-terminate the new string at that point.然后对memcpy的简单调用就是执行复制所需的全部内容,然后在此时终止新字符串。

For example, if you read with fgets() into buf and then want to separate buf into fname holding the filename and ext holding the extension, all you need is:例如,如果你用fgets()读入buf ,然后想把buf分成fname保存文件名和ext保存扩展名,你只需要:

    char buf[MAXC], fname[MAXC], ext[MAXC], *p;
     ...
    if ((p = strrchr (buf, '.'))) {         /* get pointer to last '.' */
        memcpy (fname, buf, p - buf);       /* copy chars up to last '.' */
        fname[p-buf] = 0;                   /* nul-terminate fname */
        strcpy (ext, p+1);                  /* copy extension */
    }

Notice too, that since you have a pointer to the final '.'还要注意,因为你有一个指向最后一个'.'的指针'.' , all you need to do is strcpy (ext, p+1); , 你需要做的就是strcpy (ext, p+1); to copy the extension.复制扩展名。

A short example putting it altogether, and handling the case where there is no '.'一个简短的例子,把它放在一起,处理没有'.'的情况'.' in the filename could be:在文件名中可能是:

#include <stdio.h>
#include <string.h>

#define MAXC 1024       /* if you need a constract, #define one (or moare) */ 

int main (void) {

    char buf[MAXC], fname[MAXC], ext[MAXC], *p;

    fputs ("enter filename: ", stdout);     /* prompt for filename */

    if (!fgets(buf, MAXC, stdin)) {         /* read/validate filename */
        fputs ("(user canceled input)\n", stderr);
        return 1;
    }

    buf[strcspn (buf, "\n")] = 0;           /* trim \n from end of buf */

    if ((p = strrchr (buf, '.'))) {         /* get pointer to last '.' */
        memcpy (fname, buf, p - buf);       /* copy chars up to last '.' */
        fname[p-buf] = 0;                   /* nul-terminate fname */
        strcpy (ext, p+1);                  /* copy extension */
    }
    else {  /* no '.' in buf */
        strcpy (fname, buf);                /* copy bur to fname */
        *ext = 0;                           /* make ext empty-string */
    }

    printf ("filename  : %s\n", fname);
    if (*ext)
        printf ("extension : %s\n", ext);
}

( note: you should check that fname isn't the empty-string in order to handle dot-files, etc, .somefile -- that is left to you) 注意:为了处理点文件等,您应该检查fname不是空字符串.somefile - 这是留给您的)

Example Use/Output示例使用/输出

$ ./bin/filename_ext
enter filename: somefile.ext
filename  : somefile
extension : ext

What if there is more than one '.'如果有多个'.'怎么办? in filename?在文件名中?

$ ./bin/filename_ext
enter filename: somefile.version.ext
filename  : somefile.version
extension : ext

What if there are none?如果没有呢?

$ ./bin/filename_ext
enter filename: somefilenoext
filename  : somefilenoext

It is just a much simpler way to approach the separation rather than tokenizing the line.这只是一种更简单的方法来处理分离而不是标记线。 Look things over and let me know if you have questions.仔细检查一下,如果您有任何问题,请告诉我。

而不是char *nome_backup ,声明应该是char* nome_backup

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM