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

How do i open and read text files?

Status
Not open for further replies.

marianna

Programmer
Jan 25, 2000
1
GB
How do i read in a text file so i can count the number of characters there are in eaach line?
 
Try this code:<br><br>#include &lt;iostream.h&gt;<br>#include &lt;fstream.h&gt;<br><br>void main()<br>{<br>&nbsp;&nbsp;&nbsp;char line[81];<br><br>&nbsp;&nbsp;&nbsp;ifstream in_file(&quot;your_text_file_path&quot;);<br>&nbsp;&nbsp;&nbsp;while (in_file) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;in_file.getline(line, 81);&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// here you put any special processing to line which holds the current line of the text file<br>&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;<br>}<br><br>This is the easy way using file streams. What is left to do is to make a function to calculate the number of characters.<br>The other way is a bit more difficult:<br><br>#include &lt;stdio.h&gt;<br>#include &lt;ctype.h&gt;<br><br>int main()<br>{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int c;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;FILE *fp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unsigned int count = 0;&nbsp;&nbsp;// number of characters<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// I miss the if file exist check and error handling stuff<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fp = fopen(&quot;your_file_name&quot;, &quot;r&quot;); // r - for reading, w - for writing, etc. (see MSDN help)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while ((c = fgetc(fp)) != EOF) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;count++;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fclose(fp);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printf(&quot;Characters in file: %d\n&quot;, count);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return 0;<br>}<br><br>The last example will count all the characters in the file. You can easily fit it to your own needs. Anyway I recommend you use the first method which is C++ specific. Hope this helps! ;-)<br><br>Regards...dex
 
Dear dex,<br><br>The question was posted in January and marianna has not logged on to tek-tips since February. It is very unlikely that she is still interested in this subject.<br><br>&quot;But, that's just my opinion... I could be wrong&quot;.<br>-pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top