从末尾删除一定数量的字符

罗尼科恩

在我的一项练习中,我要求用户在诸如C:\ Users \ Rony \ Desktop \ file.txt这样的计算机中插入文件地址,以进行一些更改。我将此地址保存在字符串中。因此,为了进行更改,我想将此字符串更改为tmp.txt,例如,地址现在为C:\ Users \ Rony \ Desktop \ tmp.txt。实际上,因为计算机之间的地址不同,所以我想从末尾删除第一个\所有字符并将其添加到此tmp.txt中。但我不知道为什么我的代码无法正常工作,谢谢

for (i = strlen(adress1); i > 0; i--)
{
if (adress1[i] == "\\")
  {
    adress[i] = 0;
    break;
  }
}
博伯曼

如果文件名小于新名称,则重写文件名可能会导致问题。即,已选择用户,C:\a.txt并且您要将其重命名为C:\tmp.txt这将导致错误,因为将超出数组范围。因此,您必须创建一个新的数组。下面的代码可以工作,但是看起来并不好看。由于您不熟悉字符串函数,因此我认为这可能是最好的方法。但是我强烈建议您看一下这些提供的功能,以减少编写代码的数量并提高可读性。

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

int main(int argc, char *argv[]) {
    char* p = "C:\\a.txt";
    int x; // this will hold the position of the last backslash
    int i;
    for(i = 0; p[i] != '\0'; i++){
        if(p[i] == '\\') {
            x = i;
        }
    }
    char pp[x+9];
    pp[x+8] = '\0';
    for(i = 0; i <= x; i++){
        pp[i] = p[i]; 
    }
    pp[i+0] = 't';
    pp[i+1] = 'm';
    pp[i+2] = 'p';
    pp[i+3] = '.';
    pp[i+4] = 't';
    pp[i+5] = 'x';
    pp[i+6] = 't';

    printf("%s -> %s\n", p, pp);
    return (0);
}

编辑

无需手动进行所有操作,而是可以使用内置的库函数使用这些将使代码更短并且更易于理解。

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

int main(int argc, char *argv[]) {
    char* p = "C:\\a.txt"; // the path
    char* t = "tmp.txt"; // the new name of the file
    char* e = strchr(p, '\\'); // returns a pointer to the last occurence of the backslash within the string p
    int i = (int)(e-p); // i contains the index position of the last occurence of the backslash
    char n[i+1+strlen(t)]; // create a string with max size i + 1 + length of t
    strncpy(n, p, i+1);// copy the first (i+1) characters of p to n 
    strncpy(&n[i+1], t, strlen(t)+1); // copy the whole string t and \0 to the end of the new path   
    printf("%s -> %s\n", p, n);
    return (0);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章