从 ostream 获取数据指针与数据长度, c++语言
时间: 2024-05-05 12:17:57 浏览: 9
中应该怎么做?
在C语言中,要从 ostream 获取数据指针与数据长度,可以通过以下步骤实现:
1. 使用 fprintf 函数将需要输出的数据写入 ostream。
2. 使用 fflush 函数将数据刷新到 ostream 中,确保数据已经到达。
3. 使用 ftell 函数获取当前 ostream 的位置指针,也就是数据的起始位置。
4. 使用 fseek 函数将文件指针移动到文件末尾,这样通过 ftell 函数获取的位置指针就是数据的长度。
5. 使用 rewind 函数将文件指针移动到文件开头,以便下一次操作。
示例代码如下:
```c
#include <stdio.h>
int main() {
FILE *fp = fopen("test.txt", "w");
if (!fp) {
printf("Failed to open file.\n");
return 1;
}
char data[] = "Hello, World!";
fprintf(fp, "%s", data);
fflush(fp);
long start = ftell(fp);
fseek(fp, 0, SEEK_END);
long end = ftell(fp);
long len = end - start;
printf("Data pointer: %p, length: %ld\n", data, len);
rewind(fp);
fclose(fp);
return 0;
}
```