LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Returning an array of structs from a function?

Hi all!

 

I had posted a few days ago about some software I was working on. It is for an API for a client. They wanted it in the CVI environment for their project. It's essencially a parser. So we are aiming to create a .h and .C file that has a function in it that can be called so they can parse a file and read each of the elements in a .csv file. Each line will be separated and placed in a variable in a struct that is an element in an array of structs.

 

I've developed the function. now I want to get the function to handle two arguments: an array with the filepath string stored in it, and the number of lines to read.

 

so it essentially was a function that had a void type.

 

void ParseConfigFile(char filepath[], int LinesToRead);

 I have the struct decleration defined in the header file.

 

I then declared:

 

struct TestStep TestSteps[500];

 

During debugging I was just able to print at the bottom of the function using a format like: 

 

TestSteps[LineNumber].StructElement

 

 

easily.

 

 

 

How do i convert it into a function that can be called with the arguments shown above and return the array of structs so the user can just call:

 

TestSteps[LineNumber].StructElement

 I hope that wasn't confusing.

 

 

Thanks in advance!

 

0 Kudos
Message 1 of 2
(4,105 Views)

Basically, you should be able to do something like this:

 

/// HIFN ReadFile
/// HIFN The function reads the data file and stores the content in an
/// HIFN array of structs for the caller
/// HIPAR file/The pathname of the file to read
/// HIPAR nrec/The number of records read from the file (returned to caller)
/// HIRET The allocated array of structs read from the file
/// HIRET It is responsibility of the caller to free the allocated memory
/// OUT nrec
myStruct *ReadFile (char *file, int *nrec)
{
	int	size;
	FILE	*fH = NULL;
	logRec	*xl = NULL;

// WARNING!
// Error checking must be added for all I/O operations

	// Check if file exists and calculate array size
	if (!FileExists (file, &size) || !size) {
		MessagePopup ("Read", "Either the file does not exist or there are non records to view.");
		return NULL;
	}
	*nrec = size / sizeof (myStruct);

	// Allocate and intialize memory
	xl = malloc (*nrec * sizeof (myStruct));
	memset (xl, 0, *nrec * sizeof (myStruct));

	// Open, read and close the file
	fH = fopen (LOGF, "rb");
	fread (xl, sizeof (myStruct), *nrec, fH);
	fclose (fH);

	// That's all!
	return xl;
}

 

Please take care of freeing memory after you have finished using it.



Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
0 Kudos
Message 2 of 2
(4,094 Views)