处理C linux和windows的字符串

Nic*_*las 3 c linux windows string

我是C编程的新手.我有这个问题,我不明白.看来windows下的字符串是以与linux完全不同的方式处理的,为什么呢?

Thant是我的代码

#include <stdio.h>
#include <string.h> // compare strings
void addextname(char *str1, char *str2, char *nome1){
    int i,j;
    i = 0;
    while (str1[i]!='.') {
        nome1[i] = str1[i];
        i++;
    }
    j = 0;
    while (str2[j]!='\0') {
        nome1[i] = str2[j];
        i++;
        j++;
    }
}

int main()
{
    char str1[9]="file.stl";
    char str2[9]="name.stl";
    int len1 = strlen(str1);
    int len2 = strlen(str2);
    char nome1[len1+len2+1];
    addextname(str1,str2,nome1);
    printf("%s  %s  %s\n",str1,str2,nome1);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的目的是在其扩展名(.stl)中读取输入文件名,并为其保留该扩展名添加一些字符.在linux下我没有问题,在Windows下输出文件名被无法正确保存.我的编译线是

gcc modstr.c -std=c99 -o strings
Run Code Online (Sandbox Code Playgroud)

我非常感谢你的回答!

cni*_*tar 10

你不是0终止nome1.尝试:

nome1[i] = 0; /* After the second while. */
Run Code Online (Sandbox Code Playgroud)

  • ...你应该把`while(str1 [i]!='.')`更改为`while(str1 [i]!='.'&& str1 [i]!='\ 0')`因为否则addextname将传递没有扩展名的文件名作为第一个参数时崩溃. (2认同)
  • 你应该从右边开始搜索,因为文件名可以包含多个句点. (2认同)
  • @Axel,Ignacio好电话:-)或者只是使用`strrchr`? (2认同)