c - fread() 中的索引 : Is there a way to set the minimum index to be returned?

标签 c indexing pthreads fread

上下文:

我正在尝试读取一个文件,并找出我正在读取的部分中的字符。对于这部分程序的总体方案,我使用 pthreads 和 fread()。

现在,我的代码如下所示:

  excess=( fread( thread_data[i].buffer, 1, 30, f ) );
  printf("\n\nSegFault 1 \n\n%s\n\n\n", thread_data[i].buffer);
  printf("\n\nSegFault 2 n\n%s\n\n\n", &thread_data[i].buffer[10]);

为了将所有内容放在上下文中,第一个语句是打印整个缓冲区,包括剩余的垃圾,因为我还没有设置空终止符。

然后,我们调用第二个 printf,我将获取从缓冲区中的第 10 个字符到缓冲区的最后一个字符的所有内容。例如:

 frist printf:    1234567890 abcdefgh
 second printf:   abcdefgh

问题:

如何索引缓冲区以便可以检索要玩的单个字符?如果我们看上面的例子,当我调用时:

&thread_data[i].buffer[10]

我期望返回' ',即空格

最佳答案

索引基本正确,但打印错误。您可以像这样引用缓冲区中索引 10 处的 char:

thread_data[i].buffer[10]

如果您改为获取该 char 的地址,则生成的 char * 可用于引用由以下内容组成的 C 字符串 thread_data[i].buffer 的尾部从索引 10 开始。所以试试这个:

printf("\n\nSegFault 2 n\n%c\n\n\n", thread_data[i].buffer[10]);

请注意格式字符串和参数的微小变化。

关于c - fread() 中的索引 : Is there a way to set the minimum index to be returned?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26306751/

相关文章:

c - 用制表符替换空格

c++ - 汇编代码导致递归

连续调用该函数返回相同的结果

sqlite 性能问题 : one index per table is somewhat painful

c - 多线程编程 C.互斥量不起作用

c - sprintf/snprintf 哪个更安全?

matlab - ???索引超出矩阵尺寸PSD问题

mysql - mysql 中的索引是如何工作的?

ubuntu - PThread 退出后如何回收内存?

c++ - Pthreads,与 pthread_join(pthread_t, void**) 混淆