Solved

some algorithm

Posted on 2004-04-20
8
222 Views
Last Modified: 2011-09-20
Hi experts,

int getdata(char *filename, ITEMS *items)
{
int i = 0;
char line [MAX_STR_LEN];
FILE *file_in;

if ( ( file_in = fopen (filename,"r")) == NULL) exit(EXIT_FAILURE);

 while ( fgets (line, MAX_LEN, file_in != NULL){

      sscanf (line,"%d %s", &item[i].number,item[i].string);
      i++;
 }
 return i;
}

Is this the best way to get data from a file ? How do I use malloc to replace MAX_STR_LEN so that I do not need to waste the space?
I would also like to do a timing algorithm to count the efficieny of my funtions, (eg sorting), how do I do that?
0
Comment
Question by:leeletir
8 Comments
 
LVL 22

Expert Comment

by:_TAD_
ID: 10869274


I think that your best bet is to ask this question in the C++ or C forum.  C# would only use pointers in "unsafe" code, and that would be inefficient to do a simple task like opening a file.
0
 
LVL 10

Expert Comment

by:ptmcomp
ID: 10873055
Yes, your code looks like C++
0
 

Expert Comment

by:almurray
ID: 10877263
Hi leeletir,
Before using malloc - be sure you know why you want it. It is trickier to work with than static allocation. Static memory allocation, as you have it, is fine. But if you need dynamic allocation you can use malloc to allocate memory as you require it and then free the memory at the appropriate place. I have given examples of both C (malloc and free) and C++ (new and delete) memory allocation.

use 'malloc' and 'free' if you are working in a C environement
========================================

char *line;
line= (char*)malloc(MAX_STR_LEN);

***** IMPORTANT NOTE ******
Be sure to free your memory as follows when you are finished using it otherwise you will get a memory leak, which can cause your program to crash.

free(line);
------------------------------------------------------------------------

use 'new'and 'delete' if you are working in a C++ environement
========================================

char *line;
line= new char[MAX_STR_LEN];      

now use 'line' here until you are finsihed and only thne  can you free your memory
***** IMPORTANT NOTE ******
Be sure to delete your memory as follows when you are finished using it otherwise you will get a memory leak, which can cause your program to crash.

delete [] line;
------------------------------------------------------------------------
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 14

Expert Comment

by:wayside
ID: 10878981
If your choice is between

char line[MAX_STR_LEN];

and

char *line = new char[MAX_STR_LEN];

it doesn't really matter, both use the same amount of memory. The difference is that one is on the stack and the other isn't.

If MAX_STR_LEN is small ( < 100,000, say) I wouldn't worry about wasting memory unless you have really restrictive requirements.

Could the string portion have spaces in it? If so, instead of

     sscanf (line,"%d %s", &item[i].number,item[i].string);
 
you might want to use something like

     sscanf (line,"%d %[^\r\n]", &item[i].number,item[i].string);
 
which will scan to the end of the line, rather than until the first space

> otherwise you will get a memory leak, which can cause your program to crash.

I don't see how a leak could cause a crash, unless you leak so much you run out of memory.
0
 

Expert Comment

by:almurray
ID: 10879252
The above example could cause a crash if the memory allocation is placed inside the while loop and never freed.

As memory allocation is a tricky area for newcommers to it, it is worthwhile pointing out the potential pitfalls. A worthwhile excercise for newcomers to dynamic memory allocation is to experiment a bit in a small program to get a feel for how it should and shouldn't be used. It may be even worthwhile to cause the program to crash to see it's effect, and then to try to rectify the problem.
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10897852
It looks like a C environment to me.
In C++ you better use streams ifstream or fstream.
In C++ it would be wiser to pass objects (like ITEMS) as reference and use stl containers like string dor the filename and map for the ITEMS.
0
 

Accepted Solution

by:
oldb earned 125 total points
ID: 10937573
/* nel is the number of elements */
ITEMS *getdata(char *filename){

int num,nel;
char word[MAX_STR_LEN];
FILE *file_in;
ITEMS *items;

if ( (file_in = fopen(filename,'r')) == NULL)
               error;

while ( !feof(file_in)){

         fscanf(file_in ,"%d %s" , &num,word);
         (items+nel)->string = malloc(sizeof(char)*strlen(word) );
          items = realloc( items, sizeof(ITEMS)*(nel+1) );

          (items+nel)->number = num;
          strcpy((items+nel)->string, word);
          nel++;
           }

fclose(file_in);
return items;
}
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now