|
Hello
Can anyone tell me how to read and write to a binary file?
Any sample code will be of great help.
I want to write multiple structures into a binary file
and then read it one by one.
Thanks in advance
|
|
|
|
|
Just CreateFile with binary access, write it, seek to the front, and read it back record by record. If you want random access, then the records must be the same size. If you want variable length records, just precede each binary record with a DWORD with the record size when you write it, then when you read it back, read the DWORD to get the record size, then read the data block, - this also implies that the file must be sequentially accessed both for writing and reading.
Dave.
|
|
|
|
|
#include <stdio.h>
typedef struct _myStruct
{
int x;
int y;
int z;
} myStruct;
int main()
{
FILE *fp;
char *fileName = "output.dat";
char *mode = "wb";
myStruct theArray[10];
int i;
for (i=0; i<10; i++)
{
theArray[i].x = i;
theArray[i].y = 10-i;
theArray[i].z = i * (10-i);
}
fp = fopen(fileName, mode);
fwrite(theArray, sizeof(struct myStruct), 10, fp);
fclose(fp);
}
|
|
|
|
|
Thanks for the sample code.
I am working on C++ using WIN32 API's in Visual Studio 2003.
In the function here for binart read/write,
i am using the functions, _write and _ read.
Does that make any difference in writing/reading? compared to using fwrite and fread?
|
|
|
|
|
|
dipuks wrote: i am using the functions, _write and _ read.
See here and here.
"Old age is like a bank account. You withdraw later in life what you have deposited along the way." - Unknown
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
|
|
|
|
|
For opening binary file use CreateFile [^] with OPEN_EXISTING flag.
For reading the file use ReadFile [^]
For writing the file use WriteFile [^]
Величие не Бога может быть недооценена.
|
|
|
|
|
Hi,
I have the following program.
I want to use char array at the end of while loop so that after while loop if i use printf() statement it will be printed.I have already copy the directory in an char array.Actually i am something confusing at this time and cann't solve the problem.
#include<windows.h>
#include<string.h>
#include<stdio.h>
int main()
{
int length1,length2;
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
char DirSpec[MAX_PATH + 1];
DWORD dwError;
char dirpath[MAX_PATH];
printf("Enter the path of directory: ");
gets(dirpath);
printf ("Target directory is %s\n",dirpath);
strncpy (DirSpec, dirpath, strlen(dirpath)+1);
strncat (DirSpec, "\\*", 3);
hFind = FindFirstFile(DirSpec, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
printf ("Invalid file handle. Error is %u\n", GetLastError());
return (-1);
}
else
{
length1=sizeof(FindFileData.cFileName);
char firstdir[length1];
strcpy(firstdir,FindFileData.cFileName);
printf("First file name is %s\n",firstdir);
while (FindNextFile(hFind, &FindFileData) != 0)
{
length2=sizeof(FindFileData.cFileName);
char otherdir[length2];
strcpy(otherdir,FindFileData.cFileName);
printf("Other dir is:%s\n",otherdir);
}
/* ****************************************************
* here i want a char array *
* printf("All dir except first is:%s",array); *
* *
****************************************************/
dwError = GetLastError();
FindClose(hFind);
if (dwError != ERROR_NO_MORE_FILES)
{
printf ("FindNextFile error. Error is %u\n", dwError);
return (-1);
}
}
return (0);
}
I have commented the line where i want the char array.Actually i want this array outside while loop.
|
|
|
|
|
Please post your code withing the code block.
You are more likely to get and answer if you do that.
ravi 12 wrote: char otherdir[length2]
You cannot create an array with a variable (length2) as its size.
You need to have a constant instead.
|
|
|
|
|
Hi «_Superman_»,
thank you very much for your suggestion.You are right that i must create a constant size array.thanks
|
|
|
|
|
Are you wanting a char array of all files found in the while() loop by the FindFirstFile() /FindNextFile() pair? Unless you have an aversion against it, use std::vector or std::list .
"Old age is like a bank account. You withdraw later in life what you have deposited along the way." - Unknown
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
|
|
|
|
|
Hi DavidCrow,
Thanks for your suggestion.Yes i want a char array of all files found in the while() loop by the FindFirstFile()/FindNextFile() pair.
|
|
|
|
|
Perhaps «_Superman_» overlooked the difference between c and c++ when it came to dynamically sized array declarations - they work just fine here too.
Um, this is really very easy.
You need to declare somewhere to hold a string.
After each new filename has been retrieved it's tacked onto the end of the existing string
When the loop's over the string is printed.
I can think of at least 3 ways around this mountain, though (surprise, surprise) went for the easiest/quickest/dodgiest (is that even a word?) way.
1. Declare a new var in main and initialize to 4096 times "\0" (since I'm testing in C:\ and I know there to be under 4kb worth of file/folder names there)
char finalString[4096];
2. Add to it each time through the loop
while (FindNextFile(hFind, &FindFileData) != 0)
{
strcat(finalString, FindFileData.cFileName);
strcat(finalString, "\n");
}
3. Print it out
printf("%s\n", finalString);
The other two ways that come to mind are:
1. Dynamically resizing the memory used to hold the final string.
2. Getting a count of the number of dir-entries, then creating an array of char* with that many entries. You then alloctae some memory, point dirEntryArray[curEntryNum] at this memory, and make sure you copy the current filename into said mem.
You can probably see why I went for the 'coding-horrors' way.
EDIT: ah crap! See, that's why David is an MVP, and I'm not. 
|
|
|
|
|
hi enhzflep,
very very thank of you for your suggestion.Now it works fine.Actually i was useing strcpy() function instead of strcat() function.I don't know why i was unable to do that.Thanks again..........
|
|
|
|
|
I think it will better if we can use heap allocation instead of stack for 4k, because, these 4k allocations finally leads to stack overflow. .
Ravi you can follow which ever method according to the need.
If you follow David's method then it will be less error prone and more maintainable
but enhzflep's method is much faster
Величие не Бога может быть недооценена.
modified on Friday, October 30, 2009 4:38 AM
|
|
|
|
|
I am trying to write a program as a math tutor. Can someone look at this code. I keep getting errors on int and pointer as well as telling me the switch case has illegal pointer.
Thanks, any advice would be greatful.
#include <stdio.h>
#include <stdlib.h>
#define SENT 4 //"Quit" menu choice
void DisplayMenu (void);
void GetMenuChoice (void);
void Gen2Rand (int*r1, int*r2);
void DrillOneProb (int*c, int*r1, int*r2);
int main (void)
{
int c;
int r1,
r2;
}
void DisplayMenu (void)
{
printf("MENU OF OPERATIONS\n\n");
printf("1. Addition.\n");
printf("2. Subtraction.\n");
printf("3. Multiplication.\n");
printf("4. Quit.\n\n");
}
void GetMenuChoice (void)
{
int c;
printf ("Enter the number of the operation to try (1-4):\n");
scanf ("%d", &c);
while
(c<1 || c>SENT)
printf("\aInput value is out of range.\n");
}
void Gen2Rand (int *r1p, int *r2p)
{
int c;
c=0;
if (c>=1 && c<SENT)
int r1;
int r2;
r1 = 2 + rand() %11;
r2 = 2 + rand() %11;
*r1p = r1;
*r2p = r2;
printf("Program complete\n");
}
void DrillOneProb (int *c, int *r1, int *r2)
{
int CorAns,
Reply;
{
printf("\nWhat is %d", & r1);
r1 = 2 + rand() % 11;
}
switch (c);
{
case '1': 1 = +; break;
CorAns = r1 + r2;
case '2': 2 = -; break;
CorAns = r1 - r2;
case '3': 3 = x; break;
CorAns = r1 x r2;
}
printf("%d ? %d\n", r2, Reply);
if
Reply = CorAns
{
printf("Yes, that is correct. Good Job!");
}
else
printf("No, the correct answer is: %d", CorAns);
printf("\n\n");
return (c);
print_menu();
return (0);
|
|
|
|
|
kbury wrote: switch (c);
This must be switch (c) without the ;
I also believe that it must actually be switch (*c)
|
|
|
|
|
Thanks, I just changed and it fixed that part.
|
|
|
|
|
kbury wrote: 1 = +;
kbury wrote: 2 = -;
kbury wrote: 3 = x;
kbury wrote: CorAns = r1 x r2;
kbury wrote: if
Reply = CorAns
I think you should read very carefully a syntax reference of the C programming language.
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong.
-- Iain Clarke
[My articles]
|
|
|
|
|
I am only trying to follow a flow chart given and it is very confusing. Thank you
|
|
|
|
|
While following the flow, you shouldn't forget there is also the syntax...
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong.
-- Iain Clarke
[My articles]
|
|
|
|
|
I am stuck with this section of my code so far: error codes: expected int and got pointer to int and operands of = illegaltype pointer to int and int
void DrillOneProb (int*c, int*r1, int*r2)
{
int CorAns,
Reply;
{
printf("\nWhat is %d",r1); 1st error scanf("%d", r1);
r1 = 2 + rand() % 11; 2nd error
}
|
|
|
|
|
kbury wrote: printf("\nWhat is %d",r1);
change to
printf("\nWhat is %d", *r1);
kbury wrote: r1 = 2 + rand() % 11;
change to
*r1 = 2 + rand() % 11;
The above steps, however just fix compiler errors...I don't know if the semantic will be correct.
BTW what about a good C language programming book?
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong.
-- Iain Clarke
[My articles]
|
|
|
|
|
change to
printf("\nWhat is %d", *r1); (I already changed this)I figured that out.
kbury wrote:
r1 = 2 + rand() % 11;
change to
*r1 = 2 + rand() % 11; (This defineately fixed this.
The above steps, however just fix compiler errors...I don't know if the semantic will be correct.
switch (c)
{ (states that this is illegal type pointer to int in switch expression.)
case '1':
printf("+");
CorAns = r1 + r2; (operands of + have illegal of 'pointer to int' and 'pointer to int')
break;
|
|
|
|
|
kbury wrote: CorAns = r1 + r2;
change to
CorAns = *r1 + *r2;
The real solution, however, would be reading the f*#?n' book.
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong.
-- Iain Clarke
[My articles]
|
|
|
|