Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to scan a 2 dimensional array ? Need help.

Status
Not open for further replies.

ab1966

Programmer
Jul 3, 2001
6
0
0
US
Hi,

I am reading data from a file and building an unique array of string elements. I am novice in C. So need help.

Example : I have the following arrays :

StringOfElements[TOTAL_NO_OF_ELEMENTS][LEN_OF_ELEMENT]
Elements[LEN_OF_ELEMENT]

I am reading data from file and storing it in Elements[]. Now I need scan StringOfElements for any existing element. If it is not present I am going to add it. Can anybody help me either writing the code or a function to resolve this.

Thanks in advance.
 
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define TOTAL_NO_OF_ELEMENTS 3 /* ??? */
#define LEN_OF_ELEMENT 5 /* ??? */
#define STRING_EQUAL 0

#define TRUE (1==1)
#define FALSE (!TRUE)

int main() {
/* the following is probably better named stringArr */
char StringOfElements[TOTAL_NO_OF_ELEMENTS][LEN_OF_ELEMENT] ;
/* The following is probably better named string */
char Elements[LEN_OF_ELEMENT] ;
FILE *myFile ;
int nElements = 0;
int matchFound ;
int i ;

myFile = fopen (&quot;thatFile.txt&quot;, &quot;r&quot;) ;

/* This file read my need to be more involved, */
while (fgets(Elements, LEN_OF_ELEMENT, myFile)) {

matchFound = FALSE ;
for (i = 0 ; i < nElements ; i++) {
if (strcmp(Elements, StringOfElements[ i ]) == STRING_EQUAL) {
matchFound = TRUE ;
}
}
if (!matchFound) {
/* Of course, check if we have exceed our fixed array size */
strcpy (StringOfElements[ nElements ], Elements) ; /* to be safe use strncpy */
nElements++ ;
}
}
fclose (myFile) ;

/* do something with my array */

return 0 ;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top