is random access possible on struct records in C language?

what do u mean by that ?
If u want to randomly access some struct records u can make an array of that struct and proceed........

what do u mean by that ?
If u want to randomly access some struct records u can make an array of that struct and proceed........

ya...i tried doing that....i accepted array of records in 1 program and tried to access it randomly in other program by opening the file in read mode and using fseek and fread functions....but it is showing some garbage values....so i have a doubt if we can acess struct records randomly like tat??
thanks in advance...

ya...i tried doing that....i accepted array of records in 1 program and tried to access it randomly in other program by opening the file in read mode and using fseek and fread functions....but it is showing some garbage values....so i have a doubt if we can acess struct records randomly like tat??
thanks in advance...

u are going in the exact direction.
U are getting garbage value is may be because u are not reading in the way u wrote to that file.
U have to use fwrite() for writting then only u will get correct values using fread().

typedef struct
{
 /*your data*/
} myStruct;

int index = 3; // e.g.
myStruct *buf;
int sizeOfStruct = sizeof(myStruct);
fseek(fp, sizeOfStruct*index, SEEK_SET);
if(feof(fp))
{
    cout<<"index out of bound";
    exit(1);
}
else
{
     if(fread(buf, sizeOfStruct, 1, fp)==sizeOfStruct)
     {
            /*your struct is in "buf" 
             *access its member using -> operator*/
     }
      else
      {
             /*data not present*/
             exit(1);
       }
}

and for writting u have to write as

myStruct m;
fwrite(&m, sizeOfStruct, 1, fp);

Edited 7 Years Ago by dkalita: n/a

u are going in the exact direction.
U are getting garbage value is may be because u are not reading in the way u wrote to that file.
U have to use fwrite() for writting then only u will get correct values using fread().

typedef struct
{
 /*your data*/
} myStruct;

int index = 3; // e.g.
myStruct *buf;
int sizeOfStruct = sizeof(myStruct);
fseek(fp, sizeOfStruct*index, SEEK_SET);
if(feof(fp))
{
    cout<<"index out of bound";
    exit(1);
}
else
{
     if(fread(buf, sizeOfStruct, 1, fp)==sizeOfStruct)
     {
            /*your struct is in "buf" 
             *access its member using -> operator*/
     }
      else
      {
             /*data not present*/
             exit(1);
       }
}

and for writting u have to write as

myStruct m;
fwrite(&m, sizeOfStruct, 1, fp);

end quote.

this is the program where i input struct records...

#include<stdio.h>
#include<conio.h>
struct Product
{

Edited 3 Years Ago by mike_2000_17: Fixed formatting

this is the program where i input struct records...

#include<stdio.h>
#include<conio.h>
struct Product
{

end quote.

post your program properly.

Edited 3 Years Ago by mike_2000_17: Fixed formatting

post your program properly.

this is the program where i input struct records...

#include<stdio.h>
#include<conio.h>
struct product
{
     char name[20];
      int no;
      float  price;
};
product read_rec()
{
        product p;
         printf("enter the name, number and price\n");
         scanf("%s%d%f",&p.name,&p.number,&p.price);
         return p;
}
void main()
{
       FILE *fp;
        product p[20];
       int size,i,k;
      clrscr();
       fopen=("records","w");
        if(fp==NULL)
       {
              printf("error in opening file\n");
               exit(0);
        }
        printf("enter the number of records\n");
        scanf("%d",&size);
        printf("enter the records\n");
        for(i=0;i<size;i++)
        {
                  p[i]=read_rec();
         }
          fwrite(p,(size*sizeof(p)),size,fp);
          fclose(fp);
          getch();
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

this the program where i m trying to access the records randomly....

#include<stdio.h>
#include<conio.h>
struct record
{
 char name[20];
int no;
float price;
};
void main()
{
FILE *fp;
int i;
product p[20],j;
clrscr();
fp=fopen("records","r");
printf("enter the element to accessed\n");
scanf("%d",&i);
fseek(fp,(i*sizeof(p[i])),SEEK_SET);
fread(&j,sizeof(p[i]),1,fp);
printf("name=%s\nno=%d\nprice=%f",j.name,j.no,j.price);
fclose(fp);
getch();
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

1> u are doing

fwrite(p,(size*sizeof(p)),size,fp);

which tries to write the whole things together. Better try the following in the file for writting

for(i=0;i<size;i++)
        {
                p[i]=read_rec();
                fwrite(&p[i], sizeof(product), 1, fp);
        }

and hence u wont need the p[] array u can do

product p;
//other code
for(i=0;i<size;i++)
        {
                p=read_rec();
                fwrite(&p, sizeof(product), 1, fp);
        }

test it and inform me..........

2> use CODE tag to embed codes

3> try to define struct like

typedef struct
{
      //members
} product;

That is a good practice.

4> u are writting

fseek(fp,(i*sizeof(p[i])),SEEK_SET);

u should write

fseek(fp, i*sizeof(product), SEEK_SET);

these are good programming practice

1> u are doing

fwrite(p,(size*sizeof(p)),size,fp);

which tries to write the whole things together. Better try the following in the file for writting

for(i=0;i<size;i++)
        {
                p[i]=read_rec();
                fwrite(&p[i], sizeof(product), 1, fp);
        }

and hence u wont need the p[] array u can do

product p;
//other code
for(i=0;i<size;i++)
        {
                p=read_rec();
                fwrite(&p, sizeof(product), 1, fp);
        }

test it and inform me..........

2> use CODE tag to embed codes

3> try to define struct like

typedef struct
{
      //members
} product;

That is a good practice.

4> u are writting

fseek(fp,(i*sizeof(p[i])),SEEK_SET);

u should write

fseek(fp, i*sizeof(product), SEEK_SET);

these are good programming practice

i tried doing it....but still its showing garbage values.,....what else can be done??

i tried doing it....but still its showing garbage values.,....what else can be done??

check the attachments.........
It does what u r trying to do. I have tested them

Attachments
#include<stdio.h>
typedef struct
{
	char name[20];
	int no;
	float price;
}product;
product read_rec()
{
	product p;
	printf("enter the name, number and price\n");
	scanf("%s%d%f",&p.name,&p.no,&p.price);
	return p;
}
void main()
{
	FILE *fp;
	product *p;
	p = (product *)malloc(sizeof(product));
	int index;
	fp = fopen("records","r");
	if(fp==NULL)
	{
		printf("error in opening file\n");
		exit(0);
	}

	printf("\nEnter index(>=0)=", index);
	scanf("%d", &index);

	fseek(fp, (index-1)*sizeof(product), SEEK_SET);
	if(feof(fp))
	{
		printf("index out of bound(feof)");
		return;
	}

	if(fread(p,sizeof(product), 1, fp)!=1)
	{
		printf("index out of bound(less)");
		return;
	}
	printf("%d:%s, price:%.2f\n", p->no, p->name, p->price);
	fclose(fp);
}
#include<stdio.h>
typedef struct
{
	char name[20];
	int no;
	float price;
}product;
product read_rec()
{
	product p;
	printf("enter the name, number and price\n");
	scanf("%s%d%f",&p.name,&p.no,&p.price);
	return p;
}
void main()
{
	FILE *fp;
	product p;
	int size,i,k;
	fp = fopen("records","w");
	if(fp==NULL)
	{
		printf("error in opening file\n");
		exit(0);
	}
	printf("enter the number of records\n");
	scanf("%d",&size);
	printf("enter the records\n");
	for(i=0;i<size;i++)
	{
		p=read_rec();
		fwrite(&p, sizeof(product), 1, fp);
	}
//	fwrite(p,(size*sizeof(p)),size,fp);
	fclose(fp);
}

Open/Create a data file using binary mode. c file io

FILE *fp;
fp=fopen("c:\\test.bin", "wb");
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);

Use,

int main(){
    ...
    return 0;
}

Should I use void main() or int main()?

SUMMARY:
...
main() must return int. Not void, not bool, not float. int. Just int, nothing but int, only int.
...

check the attachments.........
It does what u r trying to do. I have tested them

did read.c work??it isn't working here.....its not abt syntax errors.....but.....the records aren't getting saved in the disc....if i try to read the records from the dos shell its showing some junk values.....what could be the problem???

did read.c work??it isn't working here.....its not abt syntax errors.....but.....the records aren't getting saved in the disc....if i try to read the records from the dos shell its showing some junk values.....what could be the problem???

I have tested the read.c file in my machine which was working properly.

You can't read the doc like that since I used fwrite() which writes the stuff in binary format. U can read them using the read.c file only. Run it and see.
If u want them to be readable like that then u have to use fprintf() for writting and fscanf() for reading and in that case u wont be able to do a random access because u dont know how many bytes is taken by each data.


Read more on file operations in C/C++. U need to know more about them.

Edited 7 Years Ago by dkalita: n/a

I have tested the read.c file in my machine which was working properly.

You can't read the doc like that since I used fwrite() which writes the stuff in binary format. U can read them using the read.c file only. Run it and see.
If u want them to be readable like that then u have to use fprintf() for writting and fscanf() for reading and in that case u wont be able to do a random access because u dont know how many bytes is taken by each data.


Read more on file operations in C/C++. U need to know more about them.

i m sorry if i m being stupid......i just have a doubt.....how should i run a program from dos shell??

i m sorry if i m being stupid......i just have a doubt.....how should i run a program from dos shell??

Do u have turboC/borlandC in your machine.
If so open your file in it. In the main menu there are options for compiling and running your program.

Otherwise u have to get a copy of either turboC or borland C and put it in your machine.

After compilation u can directly run from there using the menu. Or u can exit turboC and in the command promt type the exe created by the compiler and press enter.

Do u have turboC/borlandC in your machine.
If so open your file in it. In the main menu there are options for compiling and running your program.

Otherwise u have to get a copy of either turboC or borland C and put it in your machine.

After compilation u can directly run from there using the menu. Or u can exit turboC and in the command promt type the exe created by the compiler and press enter.

i have turboc++ compiler.......running and executing is not a problem.......but i am not able to access it randomly in the second program.............

i have turboc++ compiler.......running and executing is not a problem.......but i am not able to access it randomly in the second program.............

can u send me a snapsot of the input/output for the read.c program.
Also send me a snapshot of the inputs given to the write.c program.

can u send me a snapsot of the input/output for the read.c program.
Also send me a snapshot of the inputs given to the write.c program.

output of read.c program is something like this:
enter the number of records
3
enter the name,no and price
pen
10
10
enter the name, no and price
pencil
10
10
enter the name, no and price
eraser
30
30
just a sample one........
the program is terminated there.....
output of a second program goes like this....
enter the number of record to be accessed
1
name=
number=37088
price=4372412820000000000.000000

i am not sure exactly where is the problem because when I run that program i got correct results.
Do one thing, post the two programs that u are using. I will have look at it

i am not sure exactly where is the problem because when I run that program i got correct results.
Do one thing, post the two programs that u are using. I will have look at it

ya....i ll do that....i have turbo c++ compiler 3.0 version....is tat a problem??

ya....i ll do that....i have turbo c++ compiler 3.0 version....is tat a problem??

that surely not an issue i guess

This article has been dead for over six months. Start a new discussion instead.