Thread: Trying to understand Files better

  1. #1
    Registered User
    Join Date
    Jan 2010
    Posts
    208

    Trying to understand Files better

    Code:
    using System;
    using System.IO;
    
    namespace FileExperiment
    {
        class Program
        {
            const string INPUT = "\\Projects\\FileExperiment\\FileExperiment\\Test.txt";
            const string OUTPUT = "\\Projects\\FileExperiment\\FileExperiment\\outfile.txt";
    
            static int data = 4;
            static string[] words = new string[data + 1];
    
            static StreamReader fileIn;
            static StreamWriter fileOut;
    
            static void Main()
            {
                fileIn = File.OpenText(INPUT);
                fileOut = File.CreateText(OUTPUT);
            
                InputData();
    
                for (int i = 0; i < data; i++)
                    fileOut.WriteLine("{0}",words[i]);
                Console.ReadLine();
    
    
            }
    
    
    
            static void InputData()
            {
                string word;
    
                int i = 0;
    
                while ((word = fileIn.ReadLine()) != null)
                {
                    words[i] = word;
                    i++;
                }
    
      
    
            }
    
    
        }
    }



    Can someone help me figure out why this code won't output from the input file?

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Nothing really jumps out at me unfortunately.

    Well, it could be as simple as the StreamWriter needing to be flushed. There is a StreamWriter.Flush() method for that, but I think a using block would make things easier. Using blocks also really make things easier from an RAII standpoint; ensuring that files are flushed/closed, and it's a good habit to get into now, since when you get to a bit of a higher level you will be dealing with exceptions and will want a neat approach.

    In general, paying attention to scope really helps.

    Code:
    using (StreamReader sr = File.OpenText(INPUT))
    {
       for(int i = 0; i < data + 1; i++)
       {
          words[i] = sr.ReadLine();
       }
    }
    
    using (StreamWriter sw = File.CreateText(OUTPUT))
    {
       foreach(string word in words)
       {
          sw.WriteLine(word);
       }
    }
    If code like this doesn't help then the next likely suspect is the file location. I suggest getting the environment to help you pick a good folder for your stuff.
    Environment.GetFolderPath()
    Last edited by whiteflags; 09-06-2015 at 09:43 PM. Reason: url BB-code failure

  3. #3
    Registered User
    Join Date
    Jan 2010
    Posts
    208
    now I know what I did wrong and you gave me the idea whiteflags I forgot to close the files dam I'm stupid

  4. #4
    Registered User
    Join Date
    Jan 2010
    Posts
    208
    I thought closing the files would help but it doesn't

    Your code works just fine I just don't understand why my doesn't I figured I had everything needed in there
    I was just trying to write it like my teacher does

  5. #5
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Define "doesn't work".

    Is your words[] array populated with the right number of lines? Are any of them written to the output file? Do you get any exceptions?

    I see several possible problems - mainly related to how you are coding the number of lines into the file, and you use this for output, but not for input - i.e. your input could overrun your array, or it could only partially fill it. If you actually needed to read the file into an array (rather than just immediately echo each line from input to output) you should at the very least have error checking in case I give your code a 10 line file, or a 2 line file.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  6. #6
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,868
    Add some debug code?


    Code:
    using System;
    using System.IO;
    
    namespace FileExperiment
    {
        class Program
        {
            const string INPUT = "\\Projects\\FileExperiment\\FileExperiment\\Test.txt";
            const string OUTPUT = "\\Projects\\FileExperiment\\FileExperiment\\outfile.txt";
    
            static int data = 4;
            static string[] words = new string[data + 1]; //use the +1 string to hold an error code
    
            static StreamReader fileIn;
            static StreamWriter fileOut;
    
            static void Main()
            {
                fileIn = File.OpenText(INPUT);
                fileOut = File.CreateText(OUTPUT);
    
    	    //init the array so we know if any line is empty
    	    for (int i = 0; i < data; i++)
    	    {
    	         words[i] = string.Format("No input into line number {0}.",i.ToString());
    	    }
            
                InputData();
    
                for (int i = 0; i < data; i++)
                    fileOut.WriteLine("{0}",words[i]);
    
    	    //if there was an error code then display it (write to the file?)
    	   if(words[data].Length() > 0)
    	   {
    			fileOut.WriteLine("{0}",words[data]);	
    	   }
    
                Console.ReadLine();
    
    
            }
    
    
    
            static void InputData()
            {
                string word;
    
                int i = 0;
    
                while ((word = fileIn.ReadLine()) != null)
                {
    		
    		//check for too much input
    		if(i == data)
    		{
    			words[data] = string.Format("Too many lines ({0}) in input file!", data.ToString() );
    			return;
    		}
    
                    words[i] = word;
                    i++;
    
                }
    
      	     //check we got some input
    	     if(i == 0)
    	    {
    		words[data] = string.Format("No lines in input file!");
    	    }
          }
    
    
        }
    }
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please help me understand how to think in C.
    By Strik3r in forum C Programming
    Replies: 7
    Last Post: 11-20-2011, 12:16 PM
  2. Multiple Source Files, make files, scope, include
    By thetinman in forum C++ Programming
    Replies: 13
    Last Post: 11-05-2008, 11:37 PM
  3. Something I don't understand...
    By BigFish21 in forum C Programming
    Replies: 4
    Last Post: 12-14-2007, 12:55 PM
  4. Replies: 3
    Last Post: 07-06-2006, 11:17 AM
  5. Linking header files, Source files and main program(Accel. C++)
    By Daniel Primed in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2006, 11:46 AM