1,105,320 Community Members

Reading a Text File 1 Character at a time

Member Avatar
5ophie2012
Newbie Poster
24 posts since Dec 2010
Reputation Points: 17 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Once again, I'm having trouble on my next assignment for class.

This is what I have to do:
Read and process a text file one character at a time:
1.) output the file to the screen one character at a time (as a char) as the file is read.

2.) output the file to another file called NEWFILE one
character at a time in HEX with a space between each hex character pair.
* create a method, WriteHex() for this task. use parameters to pass in the character
to be written and a reference to the output file.

3.) count each character, word & line in the file. characters can be counted in Main()
*create a method, Counts(), to count the lines and words and pass in the char,
and a reference parameter to the word and line count.

I have no idea how to even begin this.... I know I have to use the Read() method from the StreamReader class. Every time I go to output the text file as it's read using Read() method, it prints out a bunch of numbers. This is what I have so far:

using System;
using System.IO;
class TEXT
{
    static void Main()
    {
        StreamReader reader;
        reader = new StreamReader("../../../data.txt");


        do
        {
            int s = reader.Read();
            Console.WriteLine(s);
        
        
        } while (!reader.EndOfStream);
        reader.Close();
        reader.Dispose();
    
    }

    static void WriteHex(int x)
    {

    }

    static void Counts(int lines, int words)
    { 

    
    }

}

All help is appreciated! Thanks!

Member Avatar
Momerath
Senior Poster
3,821 posts since Aug 2010
Reputation Points: 1,323 [?]
Q&As Helped to Solve: 661 [?]
Skill Endorsements: 19 [?]
Featured
 
0
 

In line 13, if you are trying to read a char, why are you assigning it to an int?

Use string formating to output as hex (x.ToString("x2") for example).

You need to rethink the Counts method, as you aren't passing references or the character read at all.

Member Avatar
5ophie2012
Newbie Poster
24 posts since Dec 2010
Reputation Points: 17 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

In line 13, if you are trying to read a char, why are you assigning it to an int?

Use string formating to output as hex (x.ToString("x2") for example).

You need to rethink the Counts method, as you aren't passing references or the character read at all.

I changed the int to a char on line 13 and it comes up as an error: Cannot convert type "int" to "char". An explicit conversion exists. (Are you missing a cast?)

And as for the Counts method, should I only have 1 parameter instead of 2 since I'm "passing in the character to be written and a reference to the output file"?

Member Avatar
ddanbe
Posting Expert
5,335 posts since Oct 2008
Reputation Points: 2,054 [?]
Q&As Helped to Solve: 904 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

What you are reading in your code are in fact ASCII codes.
Change line 14 of your code into Console.Write((char)s); to see what I mean.
The cast to char is save I think, because it is a text file.
Have a look at this: http://msdn.microsoft.com/en-us/library/system.io.binaryreader.readbytes.aspx

Member Avatar
5ophie2012
Newbie Poster
24 posts since Dec 2010
Reputation Points: 17 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

What you are reading in your code are in fact ASCII codes.
Change line 14 of your code into Console.Write((char)s); to see what I mean.
The cast to char is save I think, because it is a text file.
Have a look at this: http://msdn.microsoft.com/en-us/library/system.io.binaryreader.readbytes.aspx

Thanks for the help!
I was able to read the text file 1 character at a time and display it, and count the characters in that text file (which I had no trouble with).

Now what I'm having trouble with is taking that text file, and outputting it to another text file one character at a time in HEX with a space between each hex character pair.
This is what I have so far for that:

static void WriteByte()// <<< what parameters should I have in here?
    {
        StreamWriter writer;
        writer = new StreamWriter("../../../newfile.txt");

    }
Member Avatar
ddanbe
Posting Expert
5,335 posts since Oct 2008
Reputation Points: 2,054 [?]
Q&As Helped to Solve: 904 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

If you had read completly the link I have given you, you would have noticed that at the end there are some other links for further reading. This one as an example:http://msdn.microsoft.com/en-us/library/6ka1wd3w.aspx

Member Avatar
james6754
Posting Whiz in Training
226 posts since Dec 2010
Reputation Points: 39 [?]
Q&As Helped to Solve: 22 [?]
Skill Endorsements: 4 [?]
 
0
 
string filepath = (@"C:\Documents and Settings\andre clements\Desktop\file.txt");

            int val = Convert.ToInt32(char passed in);//this would be the char passed in to method
            string hex = string.Format("{0:X}", val);
            using (StreamWriter writer = new StreamWriter(filepath))
            {
                writer.Write(hex + "  ");//hex value plus 2 spaces..
            }
Member Avatar
james6754
Posting Whiz in Training
226 posts since Dec 2010
Reputation Points: 39 [?]
Q&As Helped to Solve: 22 [?]
Skill Endorsements: 4 [?]
 
0
 

Then do that for each character read from your text file and passed in to your write method

Member Avatar
james6754
Posting Whiz in Training
226 posts since Dec 2010
Reputation Points: 39 [?]
Q&As Helped to Solve: 22 [?]
Skill Endorsements: 4 [?]
 
0
 

Or, failing that it might be easier to append each char passed in to an array then once you have all the chars in the array go ahead and print the whole lot in the array to your file?

If I am wrong..or there is a better way to do what I am saying...I would appreciate comments from the experts as I am still learning :-) Thanks

Member Avatar
5ophie2012
Newbie Poster
24 posts since Dec 2010
Reputation Points: 17 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I've been working on it....this is what I have now:

using System;
using System.IO;
public class TEXT
{
    
    public static void Main()
    {
        
        int ch, characters = 0;
        StreamReader reader;
        reader = new StreamReader("../../../data.txt");
        
        do
        {
            ch = reader.Read();
            Console.Write(Convert.ToChar(ch));
            characters++;
            
        } while (!reader.EndOfStream);

        reader.Close();
        reader.Dispose();
        Console.WriteLine(" ");
        Console.WriteLine(characters.ToString() + " characters");
        WriteByte();
    }

    public static void WriteByte(string val)
    {
        StreamWriter writer;
        writer = new StreamWriter("../../../s_drcyphert.txt");
       // I need a loop in here..not sure how to go about it
        writer.Write(val + " ");

        writer.Close();
        writer.Dispose();
    }

    public static void CountIt(int x)
    {

    }



    


}

Still having trouble with the method AFTER reading the suggested material. I'm not sure if i should be passing through a string because you cant implicitly convert a char to a string...

Any suggestions?

Member Avatar
ddanbe
Posting Expert
5,335 posts since Oct 2008
Reputation Points: 2,054 [?]
Q&As Helped to Solve: 904 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

Make line 15 and 16 to read:

ch = Convert.ToChar(reader.Read());            
Console.Write(ch.ToString());

Although the ToString could be ommited in this case.

Member Avatar
ddanbe
Posting Expert
5,335 posts since Oct 2008
Reputation Points: 2,054 [?]
Q&As Helped to Solve: 904 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

Hi harris123, post your question in a new thread, this thread is about reading a text file. Didn't you notice?

Member Avatar
5ophie2012
Newbie Poster
24 posts since Dec 2010
Reputation Points: 17 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I still haven't figured out how to write the method CountIt()..... I need to be able to count words and lines...I know that i need a bool to check and see if it's on a character or white space in order to distinguish words, and a counter for both words and lines. I'm completely stumped. I commented as much as possible to aid anyone who can help me.
- White space can be ' ' and '\r'+'\n' and '\t'
- Lines are separated by '\r'+'\n' (0d 0a)

using System;
using System.IO;
class TEXT
{
   
    static void Main()
    {
        
        int ch, characters = 0;
        StreamReader reader;
        // file that is being read in and displayed one character at a time in the console screen.
        reader = new StreamReader("../../../data.txt");
        StreamWriter writer;
        // new file where hex characters will be written to.
        writer = new StreamWriter("../../../s_drcyphert.txt");
       
        
        
        do
        {
            // read one character at a time.
            ch = reader.Read();
            // write each char to the console screen
            Console.Write((char)ch);
            // count the characters
            characters++;
            // call the WriteByte() method to write the characters to the new file
            // one character at a time in hex characters (need help with parameters and
            // what needs to be in that method).
            WriteByte(ch.ToString("x2") + " ");
            
        } while (!reader.EndOfStream);

        reader.Close();
        reader.Dispose();
        Console.WriteLine(" ");
        Console.WriteLine(characters.ToString() + " characters");
        
    }

    static void WriteByte()// <<<< help with parameters??
    {
      // needs to write each charater to the new text file as hex.
      // parameters to pass in the character to be written AND a reference to the new file
         

    }



    static void CountIt()// <<<< help with parameters??
    {
        // counts the words and lines
        // pass in the char, and a reference parameter to the word and line count
         

    }



    


}
Member Avatar
Ketsuekiame
Posting Virtuoso
1,674 posts since May 2010
Reputation Points: 793 [?]
Q&As Helped to Solve: 231 [?]
Skill Endorsements: 24 [?]
 
0
 

I still haven't figured out how to write the method CountIt()..... I need to be able to count words and lines...I know that i need a bool to check and see if it's on a character or white space in order to distinguish words, and a counter for both words and lines. I'm completely stumped. I commented as much as possible to aid anyone who can help me.
- White space can be ' ' and '\r'+'\n' and '\t'
- Lines are separated by '\r'+'\n' (0d 0a)

using System;
using System.IO;
class TEXT
{
   
    static void Main()
    {
        
        int ch, characters = 0;
        StreamReader reader;
        // file that is being read in and displayed one character at a time in the console screen.
        reader = new StreamReader("../../../data.txt");
        StreamWriter writer;
        // new file where hex characters will be written to.
        writer = new StreamWriter("../../../s_drcyphert.txt");
       
        
        
        do
        {
            // read one character at a time.
            ch = reader.Read();
            // write each char to the console screen
            Console.Write((char)ch);
            // count the characters
            characters++;
            // call the WriteByte() method to write the characters to the new file
            // one character at a time in hex characters (need help with parameters and
            // what needs to be in that method).
            WriteByte(ch.ToString("x2") + " ");
            
        } while (!reader.EndOfStream);

        reader.Close();
        reader.Dispose();
        Console.WriteLine(" ");
        Console.WriteLine(characters.ToString() + " characters");
        
    }

    static void WriteByte()// <<<< help with parameters??
    {
      // needs to write each charater to the new text file as hex.
      // parameters to pass in the character to be written AND a reference to the new file
         

    }



    static void CountIt()// <<<< help with parameters??
    {
        // counts the words and lines
        // pass in the char, and a reference parameter to the word and line count
         

    }



    


}

Are you allowed to make a copy of the characters in memory?

This way you can write the characters to a string in your application when you read them in.
Once they are into your "String", you can perform a multitude of functions on them which do the job you require.

The main one would be String.Split(params string[], StringSplitOptions); You can use this to pass in your "whitespace" strings.
Here is an example that will count the number of lines:

static void main()
{
    String myString = String.Empty;
    myString += "This is line 1\r\n";
    myString += "This is line 2\r\n";
    myString = myString + 'L' + 'I' + 'N' + 'E' + '\r' + '\n';

    Console.WriteLine(myString.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Count());
}

The console would print: 3

I will leave you to work out the word count one yourself.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article