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!

Reading an entire file into an array with C 1

Status
Not open for further replies.

OpticNurve

Programmer
Jan 27, 2002
2
US
How would I put an entire file into an array in C... where each line is an element in the array?

In perl or php its just file() ... Plus, how do I grab a certain amount of characters from that line?

For instance in PHP I would do this:

// Opens the file specified

$fp = @fopen($nsffile, "r");

// Stores it into an array - each line an element

$f_contents = file($nsffile);

// Grabs all chars from column 3 up to 16 chars on line
// $i ($i being whatever)

$aa0_subid = substr($f_contents[$i], 3, 16);


----------------------------

I would like to do this in C... anyone know how?

TIA
 
FILE cfPtr;
FileData[100][256];
int rows = 0;
if ((cfPtr = fopen("a:\file.txt", "r")) == NULL)

puts("ERROR");
while (!feof(cfPtr))
{
fgets(FileData[rows], 256, cfPtr);
rows++;
}

plus more code but this should get the data into the array

 
FILE cfPtr;
FileData[100][256];
int rows = 0;
if ((cfPtr = fopen("a:\file.txt", "r")) == NULL)

puts("ERROR");
while (!feof(cfPtr))
{
fgets(FileData[rows], 256, cfPtr);
rows++;
}

plus more code but this should get the data into the array

 
Hi Tia,

I wouldn't suggest using a static array for this purpose as the file size isn't static. Rather, its adviceable to use a linked list with a char pointer and an integer holding its length.

Read one line from the file in to a temporary buffer (of length, may be 100).

Add a node to the list, and allocate the pointer within the node, memory of the string's length.

Copy the string to the pointer and store the size of the string in the integer variable within the node.

ADVANTAGE: This will let you do SORTING easily, if you are interested. Any way this would be handy too.
Well, you may find it complicated but this is how professional programs handle varying data, such as file contents.

I could have posted a sample program to do this but it would have confused you unless you know the basic facts of pointers, structures and linked lists.

have fun coding ... ;-)

Roy.
user.gif
 
LOL, Thanks for you advice Roy but TIA means "Thanks In Advance".

Anyways... I prefer to see code examples because Im still learning c/c++ and I feel I get more out of it examining code.

I wrote a converter in perl & php and now I need to port it to C/C++.

Is there anything like substr() for C or C++?

Thanks In Advance!

- OpticNurve



 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top