如何在MMAP()输出的末端添加nullterm?

发布于 2025-01-24 13:17:33 字数 456 浏览 2 评论 0原文

通常,我将如何在MMAP()输出的末端添加零时间,以便像对待字符串一样对待它?在标记之前,我不想修改原始文件。我试图将整个文件作为字符串,但最后缺少nullterm \ 0,任何普通的字符串操作都非常困难。由于字符串文字存储在只读的内存中,而且实际上没有一种方法来改变它的大小,我该如何处理?

      int fd = fileno(fp);            // convert FILE struct to file descriptor
      char *src = mmap(0, file_size, PROT_READ, MAP_PRIVATE, fd, 0);

这是我计划的基础。我正在尝试使用许多文件操作,但是使用输出的最后一个字符来执行任何操作,最终会从内存中打印随机值,因为没有nullterm。

In general, how would I go about adding a nullterm to the end of a mmap() output, so that I can treat it like a string? Before this gets flagged, I do not want to modify the original file. I'm trying to get the entire file as a string, but the lack of a nullterm \0 on the end makes any normal string operations extremely difficult. Since string literals are stored in read-only memory, and there isn't really a way to change the size of that, how would I go about it?

      int fd = fileno(fp);            // convert FILE struct to file descriptor
      char *src = mmap(0, file_size, PROT_READ, MAP_PRIVATE, fd, 0);

This is the basis of my program. I'm attempting numerous file operations on it, but doing anything with the last character of the output ends up printing random value from memory, since there's no nullterm.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡淡绿茶香 2025-01-31 13:17:33

我想出了解决方法。我写了一个刚刚返回同一字符串的函数,但最后以零时间为单位。它不会修改原始内容,并且无论如何都不有效,但它适合我需要做的事情。我是一名学生,没有时间写入最艺术和逻辑上最完美的C代码,因此此处是 works

此功能需要字符串的大小才能参考,因此对于将来有我的问题的任何人,除了您不知道字符串的大小,那么您就不幸

// s: string to add nullterm to
// sz: size of string.
char *add_nullterm(char *s, int sz) {
  int new_sz = sz + 1;
  char temp[new_sz];

  for (int i = 0; i < sz; i++) {
    temp[i] = s[i];
  }
  temp[sz] = '\0';

  char *out = (char*)temp;
  return out;
}

I figured out a workaround. I wrote a function that just returns the same string, but with a nullterm at the end. It doesn't modify the original, and it's not efficient by any means, but it works for what I need to do. I'm a student and don't have time to write the most artistically and logically perfect C code, so here's code that works.

This function needs the size of the string for reference, so for anyone in the future who's having my problem except you don't know the size of the string, then you're out of luck

// s: string to add nullterm to
// sz: size of string.
char *add_nullterm(char *s, int sz) {
  int new_sz = sz + 1;
  char temp[new_sz];

  for (int i = 0; i < sz; i++) {
    temp[i] = s[i];
  }
  temp[sz] = '\0';

  char *out = (char*)temp;
  return out;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文