Pergunta

Eu estou usando Linux GCC c99.

Eu estou querendo saber qual seria a melhor técnica. Para alterar uma string. Eu estou usando strstr ();

Eu tenho um arquivo chamado "file.vce" e eu quero mudar a extensão para "file.wav".

Este é o melhor método:

char file_name[80] = "filename.vce";
char *new_file_name = NULL;
new_file_name = strstr(file_name, "vce");
strncpy(new_file_name, "wav", 3);
printf("new file name: %s\n", new_file_name);
printf("file name: %s\n", file_name);

Muito obrigado por qualquer conselho,


Eu editei a minha resposta usando usando suas sugestões. você pode ver qualquer outra coisa de errado?

/** Replace the file extension .vce with .wav */
void replace_file_extension(char *file_name)
{
    char *p_extension;

    /** Find the extension .vce */
    p_extension = strrchr(file_name, '.');
    if(p_extension)
    {
        strcpy(++p_extension, "wav");
    }
    else
    {
        /** Filename did not have the .vce extension */
        /** Display debug information */
    }
}

int main(void)
{
    char filename[80] = "filename.vce";

    replace_file_extension(filename);

    printf("filename: %s\n", filename);
    return 0;
}
Foi útil?

Solução

Eu faria isso

char file_name[80] = "filename.vce";
char *pExt;

pExt = strrchr(file_name, ".");
if( pExt )
  strcpy(++pExt, "wav");
else
{
 // hey no extension
}
printf("file name: %s\n", file_name);

Você precisa fazer a manipulação de ponteiros em cada programa c. Claro que você faria um pouco mais a verificação de tampão ao longo do runs etc. ou mesmo utilizar as funções específicas caminho.

Outras dicas

Existem alguns problemas com:

char file_name[80] = "filename.vce";
char *new_file_name = NULL;
new_file_name = strstr(file_name, "vce");
strncpy(new_file_name, "wav", 3);
printf("new file name: %s\n", new_file_name);
printf("file name: %s\n", file_name);

Existe apenas de armazenamento para uma cadeia, mas no final você tentar imprimir duas cadeias diferentes.

A variável chamada new_file_name realmente aponta para parte do mesmo nome.

O vce seqüência pode ocorrer em qualquer lugar dentro de um nome de arquivo, não apenas uma extensão. E se o nome do arquivo era srvce.vce?

Você provavelmente vai querer encontrar o último. caractere na seqüência, em seguida, verificar se ele é seguido pela extensão esperada, e em seguida, substituir essa extensão. E lembre-se de que se você fizer isso, modificando o tampão original, você não será capaz de imprimir a string de idade mais tarde.

Ao invés de pesquisa. ou vce qualquer dos quais pode aparecer várias vezes na cadeia, calcular o comprimento da corda e subtrair 3 a apontar para a extensão. Substitua a extensão no local usando strncpy.

size_t length;
char* pextension;
char file_name[80] = "filename.vce";
printf("file name: %s\n", file_name);    
length = strlen(file_name);
pextension = file_name + length - 3;
strncpy(pextension, "wav", 3);
printf("new file name: %s\n", file_name);

Você tem que adicionar manualmente zero terminador no final do new_file_name porque strncpy() não adicioná-lo no seu caso.

Simplesmente aconteceu que você já tem byte zero no lugar certo, mas ele não pode ser garantida em todas as situações, por isso é um bom hábito de fazer coisas como

new_file_name[3] = '\0';

depois strncpy().

Também cuidado com que string "vce" pode aparecer filename dentro.

Existem alguns problemas com o seu código. Está aqui uma tomada diferente, com as mudanças comentou em linha:

char file_name[80] = "filename.vce";
char *new_file_name = NULL;

printf("old file name: '%s'\n", file_name);
/* Use strrstr(), to find the last occurance, and include the period. */
new_file_name = strrstr(file_name, ".vce");
if(new_file_name != NULL)
{
  /* Use plain strcpy() to make sure the terminator gets there.
   * Don't forget the period.
  */
  strcpy(new_file_name, ".wav");
}
printf("new file name: '%s'\n", file_name);

Isso ainda pode ser melhorado, ele não verifica que há espaço suficiente para incluir a nova extensão, por exemplo. Mas ele faz terminar a corda, de uma forma slighly mais natural do que cutucando caracteres simples.

Eu estou entediado, e, em vez de apontar problemas no código original, eu escrevi o meu próprio. Eu tentei mantê-la clara para fins instrutivos.

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


/* Replace the last suffix in a filename with a new suffix. Copy the new
   name to a new string, allocated with malloc. Return new string. 
   Caller MUST free new string.

   If old name has no suffix, a period and the new suffix is appended
   to it. The new suffix MUST include a period it one is desired.

   Slashes are interepreted to separate directories in the filename.
   Suffixes are only looked after the last slash, if any.

   */
char *replace_filename_suffix(const char *pathname, const char *new_suffix)
{
    size_t new_size;
    size_t pathname_len;
    size_t suffix_len;
    size_t before_suffix;
    char *last_slash;
    char *last_period;
    char *new_name;

    /* Allocate enough memory for the resulting string. We allocate enough
       for the worst case, for simplicity. */
    pathname_len = strlen(pathname);
    suffix_len = strlen(new_suffix);
    new_size = pathname_len + suffix_len + 1;
    new_name = malloc(new_size);
    if (new_name == NULL)
        return NULL;

    /* Compute the number of characters to copy from the old name. */
    last_slash = strrchr(pathname, '/');
    last_period = strrchr(pathname, '.');
    if (last_period && (!last_slash || last_period > last_slash))
        before_suffix = last_period - pathname;
    else
        before_suffix = pathname_len;

    /* Copy over the stuff before the old suffix. Then append a period
       and the new suffix. */
#if USE_SPRINTF
    /* This uses snprintf, which is how I would normally do this. The
       %.*s formatting directive is used to copy a specific amount
       of text from pathname. Note that this has the theoretical
       problem with filenames larger than will fit into an integer. */
    snprintf(new_name, new_size, "%.*s%s", (int) before_suffix, pathname,
             new_suffix);
#else
    /* This uses memcpy and strcpy, to demonstrate how they might be
       used instead. Much C string processing needs to be done with
       these low-level tools. */
    memcpy(new_name, pathname, before_suffix);
    strcpy(new_name + before_suffix, new_suffix);
#endif

    /* All done. */
    return new_name;
}


int main(int argc, char **argv)
{
    int i;
    char *new_name;

    for (i = 1; i + 1 < argc; ++i) {
        new_name = replace_filename_suffix(argv[i], argv[i+1]);
        if (new_name == NULL) {
            perror("replace_filename_suffix");
            return EXIT_FAILURE;
        }
        printf("original: %s\nsuffix: %s\nnew name: %s\n",
               argv[i], argv[i+1], new_name);
        free(new_name);
    }
    return 0;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top