[英]fwrite, fread - problems with fread
I have following code: 我有以下代码:
int main()
{
char* pedal[20];
char* pedal2[20];
for (int i = 0; i < 20; i++)
{
pedal[i] = "Pedal";
}
FILE* plik;
plik = fopen("teraz.txt","wb");
for (int i = 0; i < 20; i++)
{
fwrite(pedal[i],strlen(pedal[i]),1,plik);
}
system("pause");
fclose(plik);
plik = fopen("teraz.txt","rb");
for (int i = 0; i < 20; i++)
{
fread(pedal2[i],5,1,plik); //I know for now that every element has 5 bytes
}
for (int i = 0; i < 20; i++)
{
std::cout << pedal2[i] << std::endl;
}
fclose(plik);
system("pause");
return 0;
}
It's crashing at reading and second question let's assume that I have structure where I keep like integers, floats and also char* array and how can I easly write whole structure to the file? 阅读时崩溃,第二个问题,让我们假设我拥有像整数,浮点数和char *数组一样保留的结构,如何将整个结构轻松地写入文件? Normal fwrite with sizeof structure is not working
具有sizeof结构的正常fwrite无法正常工作
Your problem that you didn't allocate buffer for reading. 您没有分配读取缓冲区的问题。 In fact line
实际上行
fread(pedal2[i],5,1,plik)
reads to unknown place. 读取到未知的地方。 You need allocate memory (in your case it is 5 + 1 bytes for zero terminated string).
您需要分配内存(在您的情况下,零终止字符串为5 + 1字节)。
pedal2[i] = malloc(5+1);
fread(pedal2[i],5,1,plik)
Don't forget to release it after usage. 使用后不要忘记释放它。
You can't read into pedal2
without first having allocated space for it. 在没有为
pedal2
分配空间之前,您无法阅读它。
You need something like this: 您需要这样的东西:
for (int i = 0; i < 20; ++i) {
pedal[i] = malloc(100); //allocate some space
}
Your first question seem to have already been answered by Simone & Dewfy. 您的第一个问题似乎已由Simone&Dewfy回答。
For your second question about how to write structure values into the file, you will have to write member by member. 关于如何将结构值写入文件的第二个问题,您将必须逐成员写入。
Please check fprintf . 请检查fprintf 。 You can probably use it for writing different data types.
您可能可以使用它来编写不同的数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.