473,769 Members | 3,305 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problems reading from an formatted file.

2 New Member
Hi:

I am trying to read from a file, which stores answers for a particular question(The answers are stop listed ). Each answer in the file is enclosed in opening and closing braces.

Here is the sample file

{ tenets nutrigenomics jim kaput improper diets risk factors disease dietary chemicals alter gene expression andor genome diseases }
{ individuals nutritional needs a result own genetic }

I am trying to read from this file and store all the answers in form of arrays. That is, each array element contains one answer. Each answer in the array element is again stored as a array of strings.

I am reading this input file using 'fscanf' function, I am able to read the first two words( tenets and nutrigenomis) properly, but when i try to read the third word in my while loop the the following string is being read( " jim kaput improper "). This string is not terminated by a null character.

I know the code can be optimized further for better performance, but besides this if you see any other problem in the code please let me know.


#define TRUE 1
#define FALSE 0
#include<stdio. h>

typedef struct answers
{

int ans_num; // stores the answer number
char data[50][20]; // stores the actual answer, we havw assumed that the length of the answer will not exceed 1000 characters
int total_num_words ; // stores the total number of answers
} ans_type;


/*
This structure is used to store information about the questions. Module number, question number, answers
related to the questions, and the total number of answers associated with the question
*/

typedef struct question_answer s
{
char module; // Stores the character associated with the module
int ques_num; // Stores the question number
ans_type ans[65]; // Stores the pointer to answers
int total_num_ans; // Stores the total number of answers

} ques_ans;

//int read_file( ques_ans *ques,char *fn)

void main()
{
FILE *fp;
int closed= TRUE;
char word[20],fn[20];
int num_ans = 0,num_words = 1,i,j;
ques_ans *ques,ques1;
ques->total_num_an s = 0;
//ques = &ques1;
//flush();
printf(" Enter the name of the file\n");
scanf("%s",fn);



if(( fp= fopen(fn,"r"))= = NULL)
{
printf("Cannot open the file\n");
return;
}

while(fscanf( fp,"%s", word) != EOF)
{

if (!strcmp(word, "{") && ( closed ==TRUE))
{
num_ans++;
closed = FALSE;

}

else if(!strcmp(word , "}") && ( closed ==FALSE))
{
closed = TRUE;

ques->ans[num_ans].total_num_word s = num_words;

num_words = 1;
}


else
{
strcpy(ques ->ans[num_ans].data[num_words], word);
num_words++;
}
}
ques-> total_num_ans = num_ans;

printf("The data collected is displayed below\n");

for(i=1; i<= ques->total_num_ans; i++)
{
printf("%d -> ",i);
for(j=1;j< ques->ans[i].total_num_word s;j++)
{
printf("%s ",ques->ans[i].data[j]);
}
printf("\n");
}

fclose(fp);
free(ques);
}
Nov 5 '07 #1
2 1479
gpraghuram
1,275 Recognized Expert Top Contributor
Hi:

I am trying to read from a file, which stores answers for a particular question(The answers are stop listed ). Each answer in the file is enclosed in opening and closing braces.

Here is the sample file

{ tenets nutrigenomics jim kaput improper diets risk factors disease dietary chemicals alter gene expression andor genome diseases }
{ individuals nutritional needs a result own genetic }

I am trying to read from this file and store all the answers in form of arrays. That is, each array element contains one answer. Each answer in the array element is again stored as a array of strings.

I am reading this input file using 'fscanf' function, I am able to read the first two words( tenets and nutrigenomis) properly, but when i try to read the third word in my while loop the the following string is being read( " jim kaput improper "). This string is not terminated by a null character.

I know the code can be optimized further for better performance, but besides this if you see any other problem in the code please let me know.


#define TRUE 1
#define FALSE 0
#include<stdio. h>

typedef struct answers
{

int ans_num; // stores the answer number
char data[50][20]; // stores the actual answer, we havw assumed that the length of the answer will not exceed 1000 characters
int total_num_words ; // stores the total number of answers
} ans_type;


/*
This structure is used to store information about the questions. Module number, question number, answers
related to the questions, and the total number of answers associated with the question
*/

typedef struct question_answer s
{
char module; // Stores the character associated with the module
int ques_num; // Stores the question number
ans_type ans[65]; // Stores the pointer to answers
int total_num_ans; // Stores the total number of answers

} ques_ans;

//int read_file( ques_ans *ques,char *fn)

void main()
{
FILE *fp;
int closed= TRUE;
char word[20],fn[20];
int num_ans = 0,num_words = 1,i,j;
ques_ans *ques,ques1;
ques->total_num_an s = 0;
//ques = &ques1;
//flush();
printf(" Enter the name of the file\n");
scanf("%s",fn);



if(( fp= fopen(fn,"r"))= = NULL)
{
printf("Cannot open the file\n");
return;
}

while(fscanf( fp,"%s", word) != EOF)
{

if (!strcmp(word, "{") && ( closed ==TRUE))
{
num_ans++;
closed = FALSE;

}

else if(!strcmp(word , "}") && ( closed ==FALSE))
{
closed = TRUE;

ques->ans[num_ans].total_num_word s = num_words;

num_words = 1;
}


else
{
strcpy(ques ->ans[num_ans].data[num_words], word);
num_words++;
}
}
ques-> total_num_ans = num_ans;

printf("The data collected is displayed below\n");

for(i=1; i<= ques->total_num_ans; i++)
{
printf("%d -> ",i);
for(j=1;j< ques->ans[i].total_num_word s;j++)
{
printf("%s ",ques->ans[i].data[j]);
}
printf("\n");
}

fclose(fp);
free(ques);
}

Hi,
If every answer is in a single line then try to use fgets to read the line and remove the braces.
Raghuram
Nov 5 '07 #2
ajay0419
2 New Member
Raghuram: Thanks fro the reply, but I need to store each word in the answer separately.
Nov 5 '07 #3

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

Similar topics

4
1978
by: Phil Grimpo | last post by:
I had previously explained this problem in a different thread, but now that I have an IISState log, I figured I'd re-start the thred. My situation and the log are following... I have a very odd situation here. I have an administration page, where based on a users permissions, a recordset is called from the SQL server which has a list of paths to "Module Menus". Each of these menus are then placed into the page by calling...
4
3738
by: hall | last post by:
Hi. I ran across a bug in one of my problems and after spending some time tracking it down i found that the problem arose in a piece of code that essentially did this: ----------- ifstream in("in.txt"); if(!in) {cout << "error\n";} in.close(); if(!in) {cout << "error\n";} in.close(); if(!in) {cout << "error\n";}
1
6252
by: inkapyrite | last post by:
Hi all. I'm using ifstream to read from a named pipe but i've encountered an annoying problem. For some reason, the program blocks on reading an ifstream's internal buffer that's only half-filled. Only when the buffer becomes full does it resume execution. Here's my test code for reading from a pipe: //(compiled with g++ -std=c++98) //--------------------------------------------- #include <iostream>
7
4221
by: laclac01 | last post by:
So I am converting some matlab code to C++. I am stuck at one part of the code. The matlab code uses fread() to read in to a vector a file. It's a binary file. The vector is made up of floats, which in matlab is 32 bits. How do I get this binary file in to floats in c++? I try reading the file using the ifstream>>myFloat. But nothing ever goes in to the float. So the closest I have come is having 4 unsigned char store the binary data....
3
1887
by: Luqman | last post by:
How can I retrieve text from html file and write to textbox. Best Regards, Luqman
1
3720
by: maztoo | last post by:
Hi I've seen this problem posted on this group in the past but I am yet to find a solution to the problem. I'm trying to import a simple spreadsheet into Access but am getting a message saying 'An error occurred trying to import the file C:\blah\blah.xls. The file was not imported'. I try and import the file by going to the file menu in Access - Get External Data - Import...
10
8357
by: Tyler | last post by:
Hello All: After trying to find an open source alternative to Matlab (or IDL), I am currently getting acquainted with Python and, in particular SciPy, NumPy, and Matplotlib. While I await the delivery of Travis Oliphant's NumPy manual, I have a quick question (hopefully) regarding how to read in Fortran written data. The data files are not binary, but ASCII text files with no formatting and mixed data types (strings, integers,...
0
1651
by: PRITPAL | last post by:
Hi There, I want a code for Saving and Reading formatted text (RTF File) in MS Access using ole Objects, i want to save 20 such records in DB using VB 6.0. Plz Help
8
1529
by: psy_berpunk | last post by:
hey, i'm trying to write a simple program to read gif87a non- interlaced format with a single image-descriptor --- I am using djgpp on windows xp. Sounds simple enough, unfortunatly data in the format is arranged primarily in single-byte unsigned integers. So i've been reading them in a chars and casting them as unsigned chars into an int.
1
9997
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8873
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3965
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.