hello sir. i am trying to create a program that will perform read/write operation on csv file. i am using structure. my structure and code is as follow:

struct item
{
    int item_no;
    char item_name[20];
    float rate;
}i1;

main()
{
.
.
fprintf(fp,"%d,%-20s,%.2f\n",i1.item_no,i1.item_name,i1.rate);
.
.
.
fscanf(fp,"%d%*c %s%*c %f",&i1.item_no,i1.item_name,&i1.rate);
printf("%d %s %.2f\n",i1.item_no,i1.item_name,i1.rate);
.
.
}

but printf is printing wrong value of rate like this:

101 Mobile 0000.00

but the actual o/p should be like:

101 Mobile 5000.00

values in item.csv file are correctly written. so i think there is problem with fscanf()
please reply me as soon as possible...
thank u in advance....

Edited 3 Years Ago by Reverend Jim: Fixed formatting

.2 is an output format specification. You are using it in your input format specification for the float.

I dont know if this is of any consequence or not but why do you have %*c in your fscanf ?

Probably to remove the comma. The asterisk in scanf means to match the specifier, then discard the result rather than store it in a variable.

This is a sample of your code, put into a program. It works fine. Note that after writing out the data (which is being done at the end of the file in this case), it's necessary to have a rewind() in there (or some other reset of the file pointer), to return the file pointer to the start of the file again.

#include <stdio.h>
#include <string.h>

struct item
{
  int item_no;
  char item_name[20];
  float rate;
}i1;

int main(void)
{
  FILE *fp = fopen("test2.txt","rw+");
  i1.item_no=101;
  strcpy(i1.item_name, "Mobile");
  i1.rate=5000.00;
  if(fp==NULL) {
    printf("Error opening file\n");
    return 1;
  }
  fprintf(fp,"%d,%-20s,%.2f\n",i1.item_no,i1.item_name,i1.rate);
  printf("%d,%-20s,%.2f\n",i1.item_no,i1.item_name,i1.rate);
  rewind(fp);
  printf("\nThe data has now been written to the file\n");
  getchar();
  fscanf(fp,"%d%*c %s%*c %f",&i1.item_no,i1.item_name,&i1.rate);
  printf("%d %s %.2f\n",i1.item_no,i1.item_name,i1.rate);
  printf("\n This is the data that was read from the file\n");
  fclose(fp);
  return 0;
}

If you'll post your code with code tags around it, I will read it more carefully than last time. I expected fully that you would be reading from the file, before you wrote data to it. ;)

i want to use pointer to structure for retrieving data from file, but i can't do.
my code is:

struct stud
{
    int roll_no,m1,m2,m3,tot;
    char name[20];
    struct stud *NEXT;
}*TEMP;
void main()
{
.
.
.
fprintf(fp,"%d%d%d%d%d%-20s",TEMP->roll_no,TEMP->m1,TEMP->m2,TEMP->m3,TEMP->tot,TEMP->name);
.
.
.
}

now i don't know how get data from file to TEMP. i tried lot but i can't do it.
so pls help me.
if possible show me method of both fread() & fscanf()

Edited 3 Years Ago by Reverend Jim: Fixed formatting

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