473,387 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

How can I write a stucture record into a text file using fwrite..

Iam trying to write student details in text file, But, i found that the file was filled with some gaurbage values.
plz anyone can help me to find the solution.

here is my code...
Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<conio.h>
  3. struct student
  4. {
  5.     char roll_no[10];
  6.     char name[10];
  7.     char previous_payment[5];
  8.     char present_payment[5];
  9.     char total_payment[5];
  10. };
  11. int toint(char str[])
  12. {
  13.     int len = strlen(str);
  14.     int i, num = 0;
  15.  
  16.     for (i = 0; i < len; i++)
  17.     {
  18.         num = num + ((str[len - (i + 1)] - '0') * pow(10, i));
  19.     }
  20.  
  21.    return num;
  22. }
  23. void tostring(char str[], int num)
  24. {
  25.     int i, rem, len = 0, n;
  26.  
  27.     n = num;
  28.     while (n != 0)
  29.     {
  30.         len++;
  31.         n = n / 10;
  32.     }
  33.     for (i = 0; i < len; i++)
  34.     {
  35.         rem = num % 10;
  36.         num = num / 10;
  37.         str[len - (i + 1)] = rem + '0';
  38.     }
  39.     str[len] = '\0';
  40. }
  41. void main()
  42. {
  43.     int previous,present,total,choice;
  44.     char ch,str1[10],str2[10];
  45.     struct student std_data;
  46.     FILE *data,*report;
  47.     printf("Enter the following details of student\n");
  48.     printf("enter roll.no of the student:");
  49.     scanf("%s",&std_data.roll_no);
  50.     printf("enter student name:");
  51.     scanf("%s",std_data.name);
  52.     printf("enter the following bill payments of Roll.no : %s \n",std_data.roll_no);
  53.     printf("Enter previous payment:");
  54.     scanf("%d",&previous);
  55.     tostring(str1,previous);
  56.     printf("str1 = %s\n",str1);
  57.     printf("Enter present payment:");
  58.     scanf("%d",&present);
  59.     tostring(str2,present);
  60.     printf("str2 = %s\n",str2);
  61.     strcpy(std_data.previous_payment,str1);
  62.     printf("std_data.previous_payment = %s\n",std_data.previous_payment);
  63.     strcpy(std_data.present_payment,str2);
  64.     printf("std_data.present_payment = %s\n",std_data.present_payment);
  65.     total = previous + present;
  66.     printf("total = %d\n",total);
  67.     tostring(std_data.total_payment,total);
  68.     printf("std_data.total_payment = %s\n",std_data.total_payment);
  69.     printf("\n");
  70.     data = fopen("student_details.txt","a");
  71.     if(data == NULL)
  72.     {
  73.         printf("error in opening input_details file\n");
  74.         exit(1);
  75.     }
  76.     fwrite(&std_data,sizeof(struct student),1,data);
  77.     fclose(data);
  78.     return;
  79. }
Sep 21 '15 #1

✓ answered by weaknessforcats

If you have a 10 char array and strcpy puts a string in there you can strlen that string to get the length of the string without the \0.

So JOHN\0 would be 4 according to strlen. That would be elements 0,1,2,3. Just move spaces into elements 4,5,6,7,8,9 and you have only data in the array.

This \0 stuff is a C convention from 1968. Various C functions are written to expect a \0. It's OK to use this internally in a program but when data goes outside the program these C conventions should not go out with the data.

If you try to the add the data in Oracle, those \0 will cause trouble. Ditto in Access and MySQL.

There s a law that says you can't read a file unless you know how it was written. I use the Method of Least Astonishment by not having weird format bytes embedded in the data.

Here's what I would do:

Create a buffer array large enough for any of your strings. Use this buffer with scanf.
Then write a Load function where you pass in your array address, the length of the array, and the address of the buffer. Internally, the load function will load the array with the number of bytes in the argument. It will start with position 0 and copy bytes from the buffer to the array one by one until it gets to the \0 in the buffer. Now it does not copy the \0 to the array but instead starts copying spaces in to the array until the array is full.

From here on you read/write the entire array.

6 1472
weaknessforcats
9,208 Expert Mod 8TB
You are writing the entire struct to the file so if your name member is John I would expect you would see John followed by six garbage values. That's because the data is 4 characters leaving six unfilled values for the rest of the 10 char array.

When writing files it's good to do so in a manner such that someone else can read them. You might consider filling the unused elements in your arrays with spaces so that a 10 element array writes 10 bytes. I would avoid writing \0 terminators to disc.

Then when you need to read the file you can read 10 bytes into the name member which is 10 bytes.

Also, do not use strcpy. It does not pay attention to your array sizes. It copies until it finds a \0. If it copies more than 9 bytes it corrupts your stack memory. Use strncpy or something like it. That way for a 10 element array you can tell strncpy to copy 10 bytes.
Sep 21 '15 #2
Just one doubt I have, you said to avoid writing \0, but in the case of scanf the function by default adds \0. So, how to handle this case.
Sep 21 '15 #3
weaknessforcats
9,208 Expert Mod 8TB
If you have a 10 char array and strcpy puts a string in there you can strlen that string to get the length of the string without the \0.

So JOHN\0 would be 4 according to strlen. That would be elements 0,1,2,3. Just move spaces into elements 4,5,6,7,8,9 and you have only data in the array.

This \0 stuff is a C convention from 1968. Various C functions are written to expect a \0. It's OK to use this internally in a program but when data goes outside the program these C conventions should not go out with the data.

If you try to the add the data in Oracle, those \0 will cause trouble. Ditto in Access and MySQL.

There s a law that says you can't read a file unless you know how it was written. I use the Method of Least Astonishment by not having weird format bytes embedded in the data.

Here's what I would do:

Create a buffer array large enough for any of your strings. Use this buffer with scanf.
Then write a Load function where you pass in your array address, the length of the array, and the address of the buffer. Internally, the load function will load the array with the number of bytes in the argument. It will start with position 0 and copy bytes from the buffer to the array one by one until it gets to the \0 in the buffer. Now it does not copy the \0 to the array but instead starts copying spaces in to the array until the array is full.

From here on you read/write the entire array.
Sep 21 '15 #4
Great I was not aware of the background of \0 and the way to use it. Thank you.
Sep 22 '15 #5
Thank u sir for your valuable suggestion.
I have one doubt sir, when i used fprintf for writing into the file i didn't get any problem and also i didn't find any gaurbage values.
But, in case of fwrite only why iam getting this problem.
Can you please explain what's the difference between these two function calls.
Sep 22 '15 #6
Expand|Select|Wrap|Line Numbers
  1. int fprintf ( FILE * stream, const char * format, ... );
  2.  
is used for printing strings. It will try to print till a null character is found. In case of
Expand|Select|Wrap|Line Numbers
  1. size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
  2.  
Writes an array of count elements, each one with a size of size bytes, from the block of memory pointed by ptr to the current position in the stream and does not look for null character, Ex: If the array size is 10 it will write all the 10 bytes into the file, so we should try to fill the non data with spaces as was explained previously. Please correct me if I am wrong.
Sep 22 '15 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: burdeen | last post by:
I can't find any way of writing a unicode, or UTF-8 format text file. Right now i have a Unicode string that i write to the text file and the unicode characters are replaced with ANSI question...
14
by: Niron kag | last post by:
Hello ! With c# , I want to write to a text file in a specific font and color. Any ideas ? Thanks...
2
by: Praveen_db2 | last post by:
Hi all Db2 8.1.3 windows Is there any way to write data into a text file using a stored procedure? The way we return a cursor output to the calling application, can we return data in a text...
2
by: asenthil | last post by:
Hai, i'm a beginner to java... just now i had tried to read and write files using java... and then i had tried to connect a database using jdbc... now i want to export the data's from a...
0
by: shakeel101 | last post by:
I'm writing a program and a part of it is supposed to read and write from a text file. Now I'm a newbie to MFC. i'm using <iostream> to read in and out, and I'm getting errors... now I've read...
1
by: rajap | last post by:
How to write all the links of the google search result page into a text file using C#.
4
by: mvvdsteen | last post by:
Hello all, I'm quite new to c++. I made a small program that will help me analyse wind tunnel data. But now I want this program to write to a text file. This works just fine, except it discards...
2
by: shivapadma | last post by:
1.i am just trying to insert a "structure record" into a file using fwrite() function by the following code 2. #include<stdio.h> #include<conio.h> struct student { char name; int rollno;...
1
by: debarun | last post by:
Simultaneous Reading and write from and to a text file using Multithreading in c/C++
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.