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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need help reading text into a 2D Array

Status
Not open for further replies.

oilerscrazy

Programmer
Jan 21, 2002
5
CA
I am stuck, I need to read text from a txt file line by line into a 2d array. I need suggestions
 
Check this code snippet...

Code:
FILE *fp;
int rows=0, idx;
char f_content[10][80]; 
//This array will hold the contents.
//ASSUMING a line in the text file wont exceed 79 chars.

if(!(fp=fopen("TextFile.txt","r")))
	{
	printf("\n\tError opening file...");
	exit(0);
	}

while(!feof(fp) && rows<10)
	fgets(f_content[rows++],80,fp);

fclose(fp);

printf(&quot;\n\tContent read from the file are...\n&quot;);

for(idx=0; idx<rows;idx++)
	printf(&quot;\nROW%d:%s&quot;,idx,f_content[idx]);

printf(&quot;\n=================End of Data==================\n&quot;);

have fun coding... ;-)

Roy.
user.gif
 
why not just use a pointer to an array of strings?

Code:
char *strings[];  // An array of strings
int iStrings = 0;

// Using fgetc()

while ( (c = fgetc(file)) != EOF) {
  sprintf(strings[iStrings] + len(strings[iStrings]), c);
  if (c == '\n')
    iStrings++;
}

Be advised...This is NOT the best way to do this, I made it to be as simple as possible. If you will be processing larger files, This routine would be a bit slow...Plus I'm at work, so gimmie a break ;)

Good luck, Rob
&quot;Programming is like art...It makes me feel like chopping my ear off.&quot;

- Currently down
 
A better way...

Code:
#define MAX_LINE_LENGTH  100  // Set this to something      
                              // reasonable

char *strings[];  // An array of strings
int iStrings = 0;

// Using fgets()

while(!feof(file)) {
  fgets(strings[iStrings], MAX_LINE_LENGTH, fp);
  iStrings++;
}
Rob
&quot;Programming is like art...It makes me feel like chopping my ear off.&quot;

- Currently down
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top