Basic File Handling and I/O

Size: px
Start display at page:

Download "Basic File Handling and I/O"

Transcription

1 Lecture #11 Introduction File and Stream I/O The System::IO namespace Basic File Handling and I/O The term basic file handling and I/O in Visual C++ refers to various file operations including read from a file, write to a file, and enumerating files in a directory, etc. Enumerating files in a directory means to retrieve a list of the files in a directory and subdirectories. File and stream I/O (input/output) refers to the transfer of data either to or from a storage medium. A file is an ordered and named collection of bytes that has persistent storage. When you work with files, you work with directory paths, disk storage, and file and directory names. In contrast, a stream is a sequence of bytes that you can use to read from and write to a backing store, which can be one of several storage mediums (for example, disks or memory). Streams involve three fundamental operations: Reading - transferring data from a stream into a data structure, such as an array of bytes. Writing - transferring data to a stream from a data source. Seeking - querying and modifying the current position within a stream. The System::IO namespace contains types that allow reading and writing to files and data streams and types that provide basic file and directory support. To use it, you need to add the following line to the top section of the file under the other using namespace lines: You can use the types in the System::IO namespace to interact with files and directories. For example, you can get and set properties for files and directories, and retrieve collections of files and directories based on search criteria. However, you need to distinguish files and directories. Again, a file is an ordered and named collection of bytes that has persistent storage. However, a directory is container that keeps the files. Here are some commonly used file and directory classes provided by the System::IO namespace to be used in this lecture: File - provides static methods for creating, copying, deleting, moving, and opening files, and helps create a FileStream object. FileInfo - provides instance methods for creating, copying, deleting, moving, and opening files, and helps create a FileStream object. Directory - provides static methods for creating, moving, and enumerating through directories and subdirectories. DirectoryInfo - provides instance methods for creating, moving, and enumerating through directories and subdirectories. Path - provides methods and properties for processing directory strings in a cross-platform manner. The path specifies where a file or a directory physically resides. For example, c:\temp\1.txt specifies that a file named 1.txt is saved under a directory named temp in the C drive. The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. For example, \\MyServer\\Shared\\1.txt means the 1.txt of a folder named Shared of a server named MyServer. In many cases, you will need to know the name of local machine s home drive (which is the drive the Windows operating system resides and running on, and is usually the C:\ drive). You can use the GetEnvironmentVariable() method of the Environment class to retrieve the value of the Windows environment variable homedrive. System::Environment::GetEnvironmentVariable("homedrive"); Visual C++ Programming Penn Wu, PhD 294

2 A sample code is: String^ hd = System::Environment::GetEnvironmentVariable("homedrive"); MessageBox::Show("Your home drive is " + hd); A sample output is: Basic File I/O In a Windows Form application, using StreamReader and StreamWriter classes of the System::IO namespace to read from or write to files is the easiest way to handle the file I/O. StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamReader for reading lines of information from a standard text file. The syntax is: StreamReader^ sr = gcnew StreamReader(path); where path is the physical address of the file, such c:\\temp\\1.txt. Notice that \\ is the sequence escape. StreamRead uses Read() or ReadLine() method of the TextReader class to read contents from a file. Read(): Reads the next character or next set of characters from the input stream. ReadLine(): Reads a line of characters from the current stream and returns the data as a string. For example, you use the following code to read contents of a text file ( C:\temp\1.txt ) in a form that has one Label control. However, you need to make sure the C:\temp\1.txt file is currently available. StreamReader^ sr = gcnew StreamReader("c:\\temp\\1.txt"); String^ line; Visual C++ Programming Penn Wu, PhD 295

3 String^ str; while ( line = sr->readline() ) str += line + "\n"; sr->close(); MessageBox::Show(str); It is always a good idea to close the file accessing object (e.g. sr) you created after you finishing accessing the file. Use the Close() method to close the current reader and release any system resources associated with the reader. sr->close(); There are many ways to determine when the end of the file is reached. You can re-write the above code to the following, which use the Peek() method of TextReader class to examine the next line before reading it. The Peek() methods returns an integer representing the next character to be read, or -1 if no more characters are available or the stream does not support seeking. StreamReader^ sr = gcnew StreamReader("c:\\temp\\1.txt"); String^ str; while ( sr->peek()!= -1 ) str += sr->readline() + "\n"; sr->close(); MessageBox::Show(str); The OpenFileDialog component is a pre-configured dialog box, which is used for file selection. You can create an instance of the StreamReader class if you prefer to work with file streams. For example, OpenFileDialog^ openfiledialog1 = gcnew OpenFileDialog;... if (openfiledialog1->showdialog() == System::Windows::Forms::DialogResult::OK) StreamReader ^ sr = gcnew StreamReader(openFileDialog1- >FileName); MessageBox::Show(sr->ReadToEnd()); sr->close(); Visual C++ Programming Penn Wu, PhD 296

4 Notice that the ShowDialog() method displays the dialog, and the ReadToEnd() method reads all characters from the current position to the end. Alternately, you can use the OpenFile() method to open the selected file. For example, if(openfiledialog1->showdialog() == System::Windows::Forms::DialogResult::OK) openfiledialog1->openfile(); The FileName property of the OpenFileDialog component can retrieve the full path of the file being selected. For example, String^ filepath = openfiledialog1->filename; StreamWriter is designed for character output in a particular Encoding, whereas classes derived from Stream are designed for byte input and output. StreamWriter^ sw = gcnew StreamWriter(path); where path is the physical address of the file in UNC format, such c:\\temp\\1.txt. StreamWriter uses either Write() or WriteLine() method of the TextWriter class to write to the stream. For example, you can write a string Welcome to CIS223! to the 1.txt file using the following code. It is necessary to note that the following code will create the c:\temp\1.txt file if it does not exist. StreamWriter^ sw = gcnew StreamWriter("c:\\temp\\1.txt"); String^ line = "Welcome to CIS223!"; // message to save sw->writeline(line); sw->close(); Similarly, the Close() closes the current writer and releases any system resources associated with the writer. The SaveFileDialog class can prompt the user to select a location for saving a file. This class cannot be inherited. The following code example illustrates creating a SaveFileDialog, setting members, calling the dialog box using the ShowDialog() method, and saving the current file. The example requires a form with a button placed on it. The RestoreDirectory property gets or sets a value indicating whether the dialog box restores the current directory before closing. The following code also uses the FilterIndex property to set which filtering option is shown first to the user. When the index is set to 2, as shown below, All files (*.*) is displayed by default. private: void button1_click(object^ sender, EventArgs^ e) Visual C++ Programming Penn Wu, PhD 297

5 Stream^ mystream; SaveFileDialog^ savefiledialog1 = gcnew SaveFileDialog; savefiledialog1->filter = "txt files (*.txt) *.txt All files (*.*) *.*"; savefiledialog1->filterindex = 2; savefiledialog1->restoredirectory = true; if ( savefiledialog1->showdialog() == ::DialogResult::OK ) if ( (mystream = savefiledialog1->openfile())!= nullptr ) mystream->close(); The Filter property gets or sets the current file name filter string, which determines the choices that appear in the "Save as file type" or "Files of type" box in the dialog box. For each filtering option, the filter string contains a description of the filter, followed by the vertical bar ( ) and the filter pattern. The strings for different filtering options are separated by the vertical bar. The following is an example of a filter string: Text files (*.txt) *.txt All files (*.*) *.* To add several filter patterns to a filter by separating the file types with semicolons, use: Image Files(*.BMP;*.JPG;*.GIF) *.BMP;*.JPG;*.GIF All files (*.*) *.* The following code demonstrates how to save the contents of a textbox to file selected by the SaveFileDialog class. The InitialDirectory property gets or sets the initial directory displayed by the file dialog box. #using <System.Drawing.dll> using namespace System::Drawing; public ref class Form1 : Form TextBox^ textbox1; public: Form1() textbox1 = gcnew TextBox; textbox1->multiline = true; textbox1->width = ClientSize.Width; textbox1->height = 220; Controls->Add(textBox1); Button^ button1 = gcnew Button; button1->text = "Save"; button1->location = Point(10, 230); button1->click += gcnew EventHandler(this, &Form1::button1_Click); Controls->Add(button1); Visual C++ Programming Penn Wu, PhD 298

6 private: Void button1_click(object^ sender, EventArgs^ e) SaveFileDialog^ savefiledialog1 = gcnew SaveFileDialog; savefiledialog1->filter = "txt files (*.txt) *.txt All files (*.*) *.*"; savefiledialog1->filterindex = 2; savefiledialog1->restoredirectory = true; if ( savefiledialog1->showdialog() == ::DialogResult::OK ) StreamWriter^ sw = gcnew StreamWriter(saveFileDialog1- >FileName); String^ line = textbox1->text; sw->writeline(line); sw->close(); MessageBox::Show("File saved as: " + savefiledialog1- >FileName); ; [STAThread] Application::Run(gcnew Form1); A sample output looks: and and The pair of StringReader and StringWriter classes are similar to StreamReader and StreamWriter except for its limitation -- strings only. StringReader: Implements a TextReader that reads from a string. StringWriter: Implements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder. For example, the following uses the str variable to read the three strings to the sr object (because the sr object has the ReadLine() method). The sw object then uses the WriteLine() methods to retrieve the string from the sr object. Visual C++ Programming Penn Wu, PhD 299

7 The output looks: String^ str = "This is the 1st string. " "This is the second string. " "This is the third string."; StringReader^ sr = gcnew StringReader(str); StringWriter^ sw = gcnew StringWriter(); sw->writeline(sr->readline()); MessageBox::Show(sw->ToString()); sr->close(); sw->close(); The following line converts the value sw holds to string and displays it in a message box. MessageBox::Show(sw->ToString()); The File class The File Class provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects. Commonly used methods are: Copy: Copies an existing file to a new file. Create: Creates a file in the specified path. Delete: Deletes the specified file. An exception is not thrown if the specified file does not exist. Exists: Determine if the given file already exists. It returns Boolean value. Move: Moves a specified file to a new location, providing the option to specify a new file name. Open: Opens a FileStream on the specified path. OpenRead: Opens an existing file for reading. OpenWrite: Opens an existing file for writing. As to the syntax, consider using the copy method as example: File.Copy(sourceFileName, destfilename, overwrite); The parameters are: sourcefilename: The file to copy. destfilename: The name of the destination file. This cannot be a directory. overwrite: A Boolean value (true or false) that tells if the destination file can be overwritten. You can visit for the syntax of using these methods. Visual C++ Programming Penn Wu, PhD 300

8 For example, the following will check if a file 1.txt already exists in the C:\temp directory. If not, it creates one. If the 1.txt file already exists, rename it to 2.txt. Notice that \\ is sequence escape. String^ str = ""; if (!File::Exists("c:\\temp\\1.txt")) File::Create("c:\\temp\\1.txt", true); str = "C:\\temp\\1.txt does not exist, but is created now."; else File::Move("c:\\temp\\1.txt", "c:\\temp\\2.txt"); str = "C:\\temp\\1.txt exist, but is renamed to c:\\temp\\2.txt."; MessageBox::Show(str); The FileInfo class allows more operations such as copying, moving, renaming, creating, opening, deleting, and appending to files. Many Visual C++ programmers prefer using the FileInfo class over the File class, probably because some of the FileInfo methods return other I/O types when creating or opening files. You can use these other types to further manipulate a file. You should know several commonly used properties (they apply to both file and directory), they are: Attributes: Gets or sets the FileAttributes of the current FileSystemInfo. CreationTime: Gets or sets the creation time of the current FileSystemInfo object. Extension: Gets the string representing the extension part of the file. FullName: Gets the full path of the directory or file. LastAccessTime: Gets or sets the time the current file or directory was last accessed. LastWriteTime: Gets or sets the time when the current file or directory was last written to. Length: Gets the size of the current file. Name: Gets the name of this DirectoryInfo instance. The syntax of using them is: objectid->propertyname For example, you can use properties of the FileInfo class to retrieve information about a file. The following use the X:\windows\Notepad.exe as target file. Visual C++ Programming Penn Wu, PhD 301

9 String^ wd = System::Environment::GetEnvironmentVariable("windir"); FileInfo^ fi = gcnew FileInfo(wd + "\\notepad.exe"); MessageBox::Show(fi->FullName + "\n" + fi->creationtime.tostring() + "\n" + fi->lastaccesstime.tostring() + "\n" + fi->lastwritetime.tostring() + "\n" + fi->length.tostring()); Notice that windir is an environment variable of Microsoft Windows operating system, which is set to the directory where WIN.COM is found. This is usually X:\WINDOWS (where X can be C, D, E, ) in case of Windows XP and Vista. The following line will force the computer to communicate with Windows operating systems to retrieve the current value of environment variable windir and assign it to wd. String^ wd = System::Environment::GetEnvironmentVariable("windir"); A sample output looks: Commonly used methods are Open, OpenRead, OpenText, CreateText, and Create. In the following example, the FileInfo class works with the OpenText() method and the StreamReader class to read a text file. If the file does not exist, the CreateText() method will create it. String^ str = ""; FileInfo^ fi = gcnew FileInfo("c:\\temp\\1.txt"); if (fi->exists == true) StreamReader^ sr = fi->opentext(); while ( sr->peek()!= -1 ) // read till the last line str += sr->readline() + "\n"; Visual C++ Programming Penn Wu, PhD 302

10 else StreamWriter^ sw = fi->createtext(); str = "1.txt is created!"; MessageBox::Show(str); You can find few methods in File class compatible to those in the FileInfo class. For example, Action File Class FileInfor Class Append text to a file File::AppendText() FileInfo::AppendText() Rename or move a file File::Move() FileInfo::MoveTo() Delete a file File::Delete() FileInfo::Delete() Copy a file File::Copy() FileInfo::CopyTo() Microsoft provides a rough guideline as to when to use them. Basically, Because all File methods are static, it might be more efficient to use a File method rather than a corresponding FileInfo instance method if you want to perform only one action. All File methods require the path to the file that you are manipulating. The static methods of the File class perform security checks on all methods. If you are going to reuse an object several times, consider using the corresponding instance method of FileInfo instead, because the security check will not always be necessary. The FileStream class can also be used to read from, write to, open, and close files on a file system, as well as to manipulate other file-related operating system handles including pipes, standard input, and standard output. Commonly used methods are: BeginRead: Begins an asynchronous read. BeginWrite: Begins an asynchronous write. Close: Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. EndRead: Waits for the pending asynchronous read to complete. EndWrite: Ends an asynchronous write, blocking until the I/O operation has completed. Read: Reads a block of bytes from the stream and writes the data in a given buffer. ReadByte: Reads a byte from the file and advances the read position one byte. Seek: Sets the current position of this stream to the given value. Write: Writes a block of bytes to this stream using data from a buffer. WriteByte: Writes a byte to the current position in the file stream. The following example uses the following syntax to read a block of bytes from the stream and writes the data in a given buffer. Read(byte[] array, int offset, int count) where, the offset parameter gives the offset of the byte in array (the buffer index) at which to begin reading, and the count parameter gives the maximum number of bytes to be read from this stream. The returned value is the actual number of bytes read, or zero if the end of the stream is reached. If the read operation is successful, the current position of the stream is advanced by the number of bytes read. If an exception occurs, the current position of the stream is unchanged. Visual C++ Programming Penn Wu, PhD 303

11 FileStream^ fs = gcnew FileStream("c:\\temp\\1.txt", FileMode::Open, FileAccess::ReadWrite, FileShare::None); array<byte>^ b = gcnew array<byte>(1024); MessageBox::Show(Convert::ToString(fs->Read(b, 0, b->length))); The FileStream class also supports some methods of the File class. For example, FileStream^ fs = File::OpenRead("c:\\temp\\1.txt"); When being used as constructor, the syntax is: FileStream(path, FileMode, FileRAccess, FileShare, buffersize, options, filesecurity) where, path: A relative or absolute path for the file that the current FileStream object will encapsulate. FileMode: A FileMode constant that determines how to open or create the file. Commonly used modes are Append, Create, CreateNew, Open, and Truncate. FileAccess: A FileSystemRights constant that determines the access rights to use when creating access and audit rules for the file. Commonly used file access options are AppendData, CreateFile, CreateDirectories, Delete, Modify, Read, ReadData, Write, and WriteData. FileShare: A FileShare constant that determines how the file will be shared by processes. Commondly used options are Delete, None, Read, ReadWrite, and Write. buffersize: A positive Int32 value greater than 0 indicating the buffer size. For buffersize values between zero and eight, the actual buffer size is set to eight bytes. options: A FileOptions constant that specifies additional file options. filesecurity: A FileSecurity constant that determines the access control and audit security for the file. For example, FileStream^ fs = gcnew FileStream("c:\\temp\\1.txt", FileMode::Append, FileAccess::Write, FileShare::Write); You can specify read and write operations to be either synchronous or asynchronous. The following example opens a file or creates it if it does not already exist, and appends information to the end of the file. #include "InputBox.cpp" FileStream^ fs = gcnew FileStream("c:\\temp\\1.txt", FileMode::Append, FileAccess::Write, FileShare::Write); Visual C++ Programming Penn Wu, PhD 304

12 fs->close(); String^ str = InputBox::Show("Write a paragraph:"); StreamWriter^ sw = gcnew StreamWriter("c:\\temp\\1.txt", true); sw->write(str); sw->close(); A sample output looks: Check the c:\temp\1.txt to verify that the entries were saved. The Directory class The Directory class is used for typical operations such as copying, moving, renaming, creating, and deleting directories. You can also use the Directory class to get and set DateTime information related to the creation, access, and writing of a directory. Commonly used methods are: CreateDirectory: Creates all the directories in a specified path. Delete: Deletes a specified directory. Exists: Determines whether the given path refers to an existing directory on disk. GetDirectories: Gets the names of subdirectories in a specified directory. GetFiles: Returns the names of files in a specified directory. As to the syntax, consider using the copy method as example: Directory::Delete(path, recursive) The parameters are: path: The name of the directory to remove. recursive: true to remove directories, subdirectories, and files in path; otherwise, false. For example, the following checks if the C:\tmp directory already exists. If so, delete the entire directory recursively. if (Directory::Exists("c:\\tmp")) Directory::Delete("c:\\tmp", true ); MessageBox::Show("c:\\tmp is deleted."); else Visual C++ Programming Penn Wu, PhD 305

13 MessageBox::Show("c:\\tmp not found."); The Directory class and work with the Drive class to list the logical drives on a computer. For example, you can declare a string array called drives and use the GetLogicalDrives() method to build up its components. The Length property counts the number of components the drives array has. The str string variable is declared and used to keep the information delivered by the GetLogicalDrives() method. cli::array<string^>^ drives = Directory::GetLogicalDrives(); int dv = drives->length; String^ str = "Available drive(s):\n"; for (int i=0; i<dv; i++) str += drives[i] +"\n"; MessageBox::Show(str); A sample output looks (note: it means the computer has C: D:, and E: logical drives): The GetCurrentDirectory() Method can return the current working directory of the application. For example, String^ cdir = Directory::GetCurrentDirectory(); MessageBox::Show("This application is in " + cdir + " directory."); Visual C++ Programming Penn Wu, PhD 306

14 The GetDirectories() method and GetFiles() method are also useful in obtaining a list of folders and a list of files in the folder. For example, you can get the information about the C:\windows directory and save the information to the C:\temp\1.txt file. String^ wd = System::Environment::GetEnvironmentVariable("windir"); cli::array<string^>^ dr = Directory::GetDirectories(wd); int n = dr->length; String^ str; for (int i=0; i<n; i++) str += dr[i] +"\n"; cli::array<string^>^ files = Directory::GetFiles(wd); int m = files->length; for (int i=0; i<m; i++) str += files[i] + "\n"; StreamWriter^ sw = gcnew StreamWriter( "c:\\temp\\1.txt" ); sw->writeline(str); sw->close(); MessageBox::Show("Saved on c:\\temp\\1.txt") Similar to the Directory class, you can use the DirectoryInfo class for typical operations such as copying, moving, renaming, creating, and deleting directories. This lecture then only introduces the properties it has. String^ sdrive = System::Environment::GetEnvironmentVariable("homedrive"); DirectoryInfo^ di = gcnew DirectoryInfo(sDrive + "\\MyDir"); String^ str; if ( di->exists ) str = "That path exists already.\n"; Visual C++ Programming Penn Wu, PhD 307

15 di->delete(); str += "But this program deleted it successfully.\n"; di->create(); str += "A new "+ sdrive + "\\MyDir is just created at:\n" + di->creationtime; MessageBox::Show(str); The above code will create a new directory named c:\mydir. A sample output looks: The following example retrieves information about the Windows directory. String^ wd = System::Environment::GetEnvironmentVariable("windir"); DirectoryInfo^ di = gcnew DirectoryInfo(wd); MessageBox::Show(di->FullName + "\n" + di->creationtime + "\n" + di->lastaccesstime + "\n" + di->lastwritetime ); A sample output looks: BinaryWriter and BinaryReader The BinaryWriter and BinaryReader classes are used for writing and reading data, rather than character strings. They are designed to write and read primitive types in binary to a stream and supports writing strings in a specific encoding. Visual C++ Programming Penn Wu, PhD 308

16 The BinaryWriter class, when being used as a constructor can initialize a new instance of the BinaryReader class based on the supplied stream and a specific character encoding. The syntax is: BinaryWriter^ ObjectID = gcnew BinaryWriter(input, encoding); where, input: The supplied stream. encoding: The character encoding. The following code example demonstrates writing data to a new, empty file stream (1.txt). Notice that the if statement will delete any existing file with the name 1.txt, and recreate a blank file named 1.txt again. After creating the file, the associated BinaryWriter and is created, and is used to write a list of integers (0 through 10) to 1.txt. However, the content of 1.txt is written in the bit-stream form, and is not readable to human. if (File::Exists("c:\\temp\\1.txt")) File::Delete("c:\\temp\\1.txt"); FileStream^ fs = gcnew FileStream("c:\\temp\\1.txt", FileMode::CreateNew); // Create the writer for data. BinaryWriter^ bw = gcnew BinaryWriter(fs); // Write data for (int i = 0; i < 11; i++) bw->write((int) i); bw->close(); fs->close(); The BinaryReader class, when being used as a constructor can initialize a new instance of the BinaryReader class based on the supplied stream and a specific character encoding. The syntax is: BinaryReader^ ObjectID = gcnew BinaryReader(input, encoding); where, input: The supplied stream. encoding: The character encoding. The following example uses the BinaryReader to read the content of 1.txt and display them in a message box. The ReadInt32() methods reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes. The BinaryReader.PeekChar() method returns the next available character and does not advance the byte or character position. Visual C++ Programming Penn Wu, PhD 309

17 The value, -1, means no more characters are available or the stream does not support seeking. Be sure the above 1.txt with bit-stream is created before executing the following code. // Create the reader for data. FileStream^ fs1 = gcnew FileStream("c:\\temp\\1.txt", FileMode::Open, FileAccess::Read); The output looks: BinaryReader^ br = gcnew BinaryReader(fs1); String^ str = ""; // Read data while (br->peekchar()!= -1) str += br->readint32() + " "; br->close(); fs1->close(); MessageBox::Show(str); Review Question 1. Which name space contains types that allow reading and writing to files and data streams and types that provide basic file and directory support? A. System B. System::IO C. System::Windows D. System::Windows::Forms 2. Which is the correct way to express a path "C:\temp\2.txt" in UNC (Universal Naming Convention) way? A. c:\temp\2.txt B. c:/temp/2.txt C. C:\\temp\\2.txt D. C://temp//2.txt 3. Which method can be used to retrieve values of Windows environment variables, such as "homedrive"? A. GetEnvironmentVariable() Visual C++ Programming Penn Wu, PhD 310

18 B. EnvironmentVariable() C. Get() D. GetEnvironment() 4. Which method reads the next character or next set of characters from input stream? A. Read() B. ReadLine C. ReadToEnd() D. ReadNext() 5. After initializing a StreamReader object "sr", which method can destroy the sr object? A. sr->remove() B. sr->destroy() C. sr->delete() D. sr->close() 6. Which property of the FileInfo class gets the name of this FileInfo instance? A. Name B. FileName C. FileInfoName D. FileInfoObjectName 7. Given the following code segment, which statement is correct? if (Directory::Exists("c:\\tmp")) Directory::Delete("c:\\tmp", true ); A. It checks if the C:\tmp directory already exists. If so, delete the entire directory recursively. B. It checks if the C:\tmp directory already exists. If so, delete the every files in it. C. It checks if the C:\tmp directory already exists. If so, delete the every sub-directory in it. D. It deletes the C:\tmp directory, and then checks to make sure the deletion is completed. 8. Given the following code segment, what does the Length property do? cli::array<string^>^ drives = Directory::GetLogicalDrives(); int dv = drives->length; A. It displays the total amount characters the directory name has. B. It counts the number of files in the directory. C. It counts the number of components the drives array has. D. It displays each directory's name in an alphabetical order. 9. Which class is used for writing data in binary, rather than character strings? A. FileWriter B. StringWriter C. StreamWriter D. BinaryWriter 10. The methods reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes. A. ReadInt16() B. ReadInt32() C. ReadInt64() D. ReadInt128() Visual C++ Programming Penn Wu, PhD 311

19 Lab #11 Basic File Handling and I/O Learning Activity #1: Creating directory and file and write to the file 1. If the C:\test directory already exists, delete it before you advance to the next step. 2. Create a directory C:\cis223 if it does not exist. 3. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223 directory. 4. Type cd c:\cis223 and press [Enter] to change to the C:\cis223 directory. C:\Program Files\Microsoft Visual Studio\2017\Community>cd c:\cis Type notepad lab11_1.cpp and press [Enter] to use Notepad to create a new empty file named C:\cis223\lab11_1.cpp. C:\cis223>notepad lab11_1.cpp 6. Enter the following codes: String^ sdrive = System::Environment::GetEnvironmentVariable("homedrive"); String^ msg = ""; if (!Directory::Exists(sDrive + "\\test")) Directory::CreateDirectory(sDrive + "\\test"); msg += "The \'" + sdrive + "\\test\' folder is just created!\n"; else msg = "The \'" + sdrive + "\\test\' folder already exists!\n"; if (!File::Exists(sDrive + "\\test\\1.txt")) StreamWriter^ sw = File::CreateText(sDrive + "\\test\\1.txt"); sw->writeline("this is the first line."); sw->writeline("this is the second line."); sw->writeline("this is the third line."); sw->writeline("this is the fourth line."); sw->close(); msg += "The \'" + sdrive + "\\test\\1.txt\' file is created!\n"; else msg += "The \'" + sdrive + "\\test\\1.txt' file also exists!\n"; MessageBox::Show(msg); return 0; Visual C++ Programming Penn Wu, PhD 312

20 7. Type cl /clr lab11_1.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile the program. C:\cis223>cl /clr lab11_1.cpp /link /subsystem:windows /ENTRY:main 8. Type lab11_1.exe and press [Enter] to test the program. It creates the X:\test (where X is usually C, but be sure to use the correct one) directory if it does not exist. 9. It also creates a new file X:\test\1.txt with the following contents: This is the first line. This is the second line. This is the third line. This is the fourth line. 10. Find the X:\test\1.txt file and open it to verify the contents. 11. Download the assignment template, and rename it to lab11.doc if necessary. Capture a screen shot similar to the above figure and paste it to the Word document named lab11.doc (or.docx). Learning Activity #2: Reading a text file 1. Make sure the c:\test directory and c:\test\1.txt file (you had created them as product of learning activity #1) exist. 2. In the C:\cis223 directory, use Notepad to create a new text file name lab11_2.cpp with the following contents: #using <System.Drawing.dll> using namespace System::Drawing; public ref class Form1: public Form Label^ label1; public: Form1() label1 = gcnew Label; label1->size = Drawing::Size(280,300); label1->location = Point(10, 10); this->controls->add(label1); this->size = Drawing::Size(300,300); String^ sdrive = System::Environment::GetEnvironmentVariable("homedrive"); StreamReader^ sr1 = gcnew StreamReader(sDrive +"\\test\\1.txt"); String^ line; Visual C++ Programming Penn Wu, PhD 313

21 label1->text = "As long as there is a line of content, read it:\n"; while ( line = sr1->readline() ) label1->text += line + "\n"; StreamReader^ sr2 = gcnew StreamReader(sDrive +"\\test\\1.txt"); label1->text += "\n\nuse Peek() method to check detect the last line:\n"; while ( sr2->peek()!= -1 ) label1->text += sr2->readline() + "\n"; sr1->close(); sr2->close(); ; [STAThread] Application::Run(gcnew Form1); 3. Type cl /clr lab11_2.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile the code. 4. Type lab11_2 and press [Enter] to test the program. 5. Capture a screen shot similar to the above figure and paste it to the Word document named lab11.doc (or.docx). Learning Activity #3: Creating and Writing to a text file 1. In the C:\cis223 directory, use Notepad to create a new text file name lab11_3.cpp with the following codes: #using <System.Drawing.dll> using namespace System::Drawing; public ref class Form1 : Form Visual C++ Programming Penn Wu, PhD 314

22 TextBox^ textbox1; public: Form1() textbox1 = gcnew TextBox; textbox1->multiline = true; textbox1->width = ClientSize.Width; textbox1->height = 220; Controls->Add(textBox1); Button^ button1 = gcnew Button; button1->text = "Save"; button1->location = Point(10, 230); button1->click += gcnew EventHandler(this, &Form1::button1_Click); Controls->Add(button1); private: Void button1_click(object^ sender, EventArgs^ e) String^ sdrive = System::Environment::GetEnvironmentVariable("homedrive"); SaveFileDialog^ savefiledialog1 = gcnew SaveFileDialog; savefiledialog1->initialdirectory = sdrive; savefiledialog1->filter = "txt files (*.txt) *.txt All files (*.*) *.*"; savefiledialog1->filterindex = 2; savefiledialog1->restoredirectory = true; if ( savefiledialog1->showdialog() == ::DialogResult::OK ) StreamWriter^ sw = gcnew StreamWriter(saveFileDialog1->FileName); String^ line = textbox1->text; sw->writeline(line); sw->close(); MessageBox::Show("File saved as: " + savefiledialog1->filename); ; [STAThread] Application::Run(gcnew Form1); 2. Type cl /clr lab11_3.cpp /link /subsystem:windows /ENTRY:main to compile the program. 3. Type lab11_3.exe and press [Enter] to launch the program. Visual C++ Programming Penn Wu, PhD 315

23 4. Test the program. In the textbox, type in the following paragraphs. Water with trace amounts of radioactivity may have leaked for months from a U.S. Navy nuclear-powered submarine as it traveled around the Pacific to ports in Guam, Japan and Hawaii, Navy officials told CNN on Friday. The leak was found on the USS Houston, a Los Angeles-class fast attack submarine, after it went to Hawaii for routine maintenance last month, Navy officials said. Just two weeks ago, thousands of Japanese protested the pending arrival of the George Washington. 5. Click the Save button. The following pop-up window appears. and and 6. Check if the specified text is saved. 7. Capture a screen shot similar to the above figure and paste it to the Word document named lab11.doc (or.docx). Learning Activity #4: Using OpenFileDialog to pick and retrieve file information 1. In the C:\cis223 directory, use Notepad to create a new text file name lab11_4.cpp with the following codes: #using <System.Drawing.dll> using namespace System::Drawing; public ref class Form1: public Form OpenFileDialog^ openfiledialog1; TextBox^ textbox1; public: Form1() Button^ button1 = gcnew Button; button1->location = Point(10, 10); button1->text = "Browse"; button1->click += gcnew System::EventHandler(this, &Form1::button1_Click); Controls->Add(button1); textbox1 = gcnew TextBox; textbox1->size = Drawing::Size(260, 200); textbox1->location = Point(10, 50); textbox1->multiline = true; Controls->Add(textBox1); Visual C++ Programming Penn Wu, PhD 316

24 private: Void button1_click( Object^ sender, EventArgs^ e) openfiledialog1 = gcnew OpenFileDialog; if(openfiledialog1->showdialog() == System::Windows::Forms::DialogResult::OK) String^ filepath = openfiledialog1->filename; FileInfo^ fi = gcnew FileInfo(filePath); textbox1->text = fi->fullname + Environment::NewLine + fi->creationtime.tostring() + Environment::NewLine + fi->lastaccesstime.tostring() + Environment::NewLine + fi->lastwritetime.tostring() + Environment::NewLine + fi->length.tostring(); ; [STAThread] Application::Run(gcnew Form1); 2. Type cl /clr lab11_4.cpp /link /subsystem:windows /ENTRY:main to compile the program. 3. Test the program. The following OpenFileDialog window opens:: 4. Pick any file and then click Open. A message box similar to the following opens: 5. Capture a screen shot similar to the above figure and paste it to the Word document named lab11.doc (or.docx). Learning Activity #5: Retrieving and saving directory information 1. Make sure the X:\test directory exist, where X is the home drive. 2. Use Notepad to create a new file named lab11_5.cpp with the following contents: Visual C++ Programming Penn Wu, PhD 317

25 String^ sdrive = System::Environment::GetEnvironmentVariable("homedrive"); StreamWriter^ sw = gcnew StreamWriter(sDrive +"\\test\\1.txt"); cli::array<string^>^ drives = Directory::GetLogicalDrives(); int dv = drives->length; sw->writeline("your computer has the following drives:\n"); for (int i=0; i<dv; i++) sw->writeline("\t" + drives[i]); sw->writeline(" "); sw->writeline("the system drive (home drive) is: " + sdrive); String^ wd = System::Environment::GetEnvironmentVariable("windir"); sw->writeline(" "); sw->writeline("the system directory is: " + wd + ", and it has the following subdirectories:"); cli::array<string^>^ dr = Directory::GetDirectories(wd); int n = dr->length; for (int i=0; i<n; i++) sw->writeline("\t" + dr[i]); sw->writeline(" "); sw->writeline("it also has the following files:"); cli::array<string^>^ files = Directory::GetFiles(wd); int m = files->length; for (int i=0; i<m; i++) sw->writeline("\t" + files[i]); sw->writeline(" "); sw->close(); String^ str; str = "The report is saved to " + sdrive +"\\test\\1.txt"; MessageBox::Show(str); return 0; 3. Compile and test the code. A sample outputs looks: Visual C++ Programming Penn Wu, PhD 318

26 4. A sample report looks: 5. Capture a screen shot similar to the above figure and paste it to the Word document named lab11.doc (or.docx). Submittal 1. Complete all the 5 learning activities and the programming exercise in this lab. 2. Create a.zip file named lab11.zip containing ONLY the following self-executable files. lab11_1.exe lab11_2.exe lab11_3.exe lab11_4.exe lab11_5.exe lab11.doc (or lab11.docx or.pdf) [You may be given zero point if this Word document is missing] 3. Log in to Blackboard, and enter the course site. 4. Upload the zipped file to Question 11 of Assignment 11 as response. 5. Upload ex11.zip file to Question 12 as response. Note: You will not receive any credit if you submit file(s) to the wrong question. Programming Exercise 11: 1. Launch the Developer Command Prompt. 2. Use Notepad to create a new text file named ex11.cpp. 3. Add the following heading lines (Be sure to use replace [YourFullNameHere] with the correct one). //File Name: ex11.cpp //Programmer: [YourFullNameHere] 4. Write codes that will check if the C:\temp223 directory exits. If so, check whether or not a text file named myplan.txt is stored under the C:\temp223 directory. If the myplan.txt file does not exist, you program must create it immediately. 5. If the C:\temp223 directory does not exit, your program must be able to create the directory and then immediately create a text file named myplan.txt and save it under the C:\temp223 directory. 6. Open the C:\temp223\myplan.txt file and add the following line to it. (It s OK to overwrite the existing content). YourFullName wrote this code. 7. Compile the source code to produce executable code. Visual C++ Programming Penn Wu, PhD 319

27 and 9. Download the programming exercise template, and rename it to ex11.doc if necessary. Capture Capture a screen similar to the above two figures and paste it to the Word document named ex11.doc (or.docx). 10. Compress the source file (ex11.cpp), executable code (ex11.exe), and Word document (ex11.doc) to a.zip file named ex11.zip. Grading criteria: You will earn credit only when the following requirements are fulfilled. No partial credit is given. You successfully submit both source file and executable file. Your program must meet all requirements. Your source code must be fully functional and may not contain syntax errors in order to earn credit. Your executable file (program) must be executable to earn credit. Threaded Discussion Note: Students are required to participate in the thread discussion on a weekly basis. Student must post at least two messages as responses to the question every week. Each message must be posted on a different date. Grading is based on quality of the message. Question: Class, what is the advantage(s) or disadvantage(s) of using a "handle" while retrieving and updating content of a file? Can Visual C++ completely eliminate the need of using a "handle" for coding feature of file input and output? [There is never a right-or-wrong answer for this question. Please free feel to express your opinion.] Be sure to use proper college level of writing. Do not use texting language. Visual C++ Programming Penn Wu, PhD 320

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms; Lecture #13 Introduction Exception Handling The C++ language provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. Exceptions

More information

Operating System x86 x64 ARM Windows XP Windows Server 2003 Windows Vista Windows Server 2008 Windows 7 Windows Server 2012 R2 Windows 8 Windows 10

Operating System x86 x64 ARM Windows XP Windows Server 2003 Windows Vista Windows Server 2008 Windows 7 Windows Server 2012 R2 Windows 8 Windows 10 Lecture #1 What is C++? What are Visual C++ and Visual Studio? Introducing Visual C++ C++ is a general-purpose programming language created in 1983 by Bjarne Stroustrup. C++ is an enhanced version of the

More information

However, it is necessary to note that other non-visual-c++ compilers may use:

However, it is necessary to note that other non-visual-c++ compilers may use: Lecture #2 Anatomy of a C++ console program C++ Programming Basics Prior to the rise of GUI (graphical user interface) operating systems, such as Microsoft Windows, C++ was mainly used to create console

More information

Table 1: Typed vs. Generic Codes Scenario Typed Generic Analogy Cash Only Multiply Payment Options. Customers must pay cash. No cash, no deal.

Table 1: Typed vs. Generic Codes Scenario Typed Generic Analogy Cash Only Multiply Payment Options. Customers must pay cash. No cash, no deal. Lecture #15 Overview Generics in Visual C++ C++ and all its descendent languages, such as Visual C++, are typed languages. The term typed means that objects of a program must be declared with a data type,

More information

Calling predefined. functions (methods) #using <System.dll> #using <System.dll> #using <System.Windows.Forms.dll>

Calling predefined. functions (methods) #using <System.dll> #using <System.dll> #using <System.Windows.Forms.dll> Lecture #5 Introduction Visual C++ Functions A C++ function is a collection of statements that is called and executed as a single unit in order to perform a task. Frequently, programmers organize statements

More information

Files. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Files. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies 12 Working with Files C# Programming: From Problem Analysis to Program Design 2nd Edition David McDonald, Ph.D. Director of Emerging Technologies Chapter Objectives Learn about the System.IO namespace

More information

#using <System.dll> #using <System.Windows.Forms.dll>

#using <System.dll> #using <System.Windows.Forms.dll> Lecture #8 Introduction.NET Framework Regular Expression A regular expression is a sequence of characters, each has a predefined symbolic meaning, to specify a pattern or a format of data. Social Security

More information

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms; Lecture #12 Handling date and time values Handling Date and Time Values In the.net Framework environment, the DateTime value type represents dates and times with values ranging from 12:00:00 midnight,

More information

F# - BASIC I/O. Core.Printf Module. Format Specifications. Basic Input Output includes

F# - BASIC I/O. Core.Printf Module. Format Specifications. Basic Input Output includes F# - BASIC I/O http://www.tutorialspoint.com/fsharp/fsharp_basic_io.htm Copyright tutorialspoint.com Basic Input Output includes Reading from and writing into console. Reading from and writing into file.

More information

Windows File I/O. Files. Collections of related data stored on external storage media and assigned names so that they can be accessed later

Windows File I/O. Files. Collections of related data stored on external storage media and assigned names so that they can be accessed later Windows File I/O Files Collections of related data stored on external storage media and assigned names so that they can be accessed later Entire collection is a file A file is made up of records One record

More information

Data Source. Application. Memory

Data Source. Application. Memory Lecture #14 Introduction Connecting to Database The term OLE DB refers to a set of Component Object Model (COM) interfaces that provide applications with uniform access to data stored in diverse information

More information

C# Data Manipulation

C# Data Manipulation C# Data Manipulation Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2018/19 H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC

More information

Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation, and definition

Term Object-Oriented Paradigm Real-life example Abstraction Class declaration, creation, and definition Lecture #6 What is a class and what is an object? Object-Oriented Programming Assuming that the instructor found a new breed of bear and decided to name it Kuma. In an email, the instructor described what

More information

Files and Streams. Today you will learn. Files and Web Applications File System Information Reading and Writing with Streams Allowing File Uploads

Files and Streams. Today you will learn. Files and Web Applications File System Information Reading and Writing with Streams Allowing File Uploads Files and Streams Today you will learn Files and Web Applications File System Information Reading and Writing with Streams Allowing File Uploads CSE 409 Advanced Internet Technology Files and Web Applications

More information

C# Data Manipulation

C# Data Manipulation C# Data Manipulation Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2018/19 H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC

More information

File Handling Programming 1 C# Programming. Rob Miles

File Handling Programming 1 C# Programming. Rob Miles 08101 Programming 1 C# Programming Rob Miles Files At the moment when our program stops all the data in it is destroyed We need a way of persisting data from our programs The way to do this is to use files

More information

Car. Sedan Truck Pickup SUV

Car. Sedan Truck Pickup SUV Lecture #7 Introduction Inheritance, Composition, and Polymorphism In terms of object-oriented programming, inheritance is the ability that enables new classes to use the properties and methods of existing

More information

05/31/2009. Data Files

05/31/2009. Data Files Data Files Store and retrieve data in files using streams Save the values from a list box and reload for the next program run Check for the end of file Test whether a file exists Display the standard Open

More information

Chapter 11. Data Files The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Chapter 11. Data Files The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill Chapter 11 Data Files McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter Objectives Store and retrieve data in files using streams Save the values from a list box and reload

More information

Industrial Programming

Industrial Programming Industrial Programming Lecture 6: C# Data Manipulation Industrial Programming 1 The Stream Programming Model File streams can be used to access stored data. A stream is an object that represents a generic

More information

How to read/write text file

How to read/write text file How to read/write text file Contents Use StreamWriter... 1 Create button click event handler... 2 Create StreamWriter... 3 Write to file... 5 Close file... 8 Test file writing... 9 Use StreamReader...

More information

#using <System.dll> #using <System.Windows.Forms.dll> #using <System.Drawing.dll>

#using <System.dll> #using <System.Windows.Forms.dll> #using <System.Drawing.dll> Lecture #9 Introduction Anatomy of Windows Forms application Hand-Coding Windows Form Applications Although Microsoft Visual Studio makes it much easier for developers to create Windows Forms applications,

More information

CSC 415 ONLINE PHOTOALBUM: THE SEQUEL ASP.NET VERSION

CSC 415 ONLINE PHOTOALBUM: THE SEQUEL ASP.NET VERSION CSC 415 ONLINE PHOTOALBUM: THE SEQUEL ASP.NET VERSION GODFREY MUGANDA In this project, you will convert the Online Photo Album project to run on the ASP.NET platform, using only generic HTTP handlers.

More information

Chapter 8 Files. File Streams

Chapter 8 Files. File Streams Chapter 8 Files Few programs are written that don t involve some type of file input/output. Way back in the days when the C language became popular a set of library functions were designed that have been

More information

public class Animal // superclass { public void run() { MessageBox.Show("Animals can run!"); } }

public class Animal // superclass { public void run() { MessageBox.Show(Animals can run!); } } Lecture #8 What is inheritance? Inheritance and Polymorphism Inheritance is an important object-oriented concept. It allows you to build a hierarchy of related classes, and to reuse functionality defined

More information

C# 2008 and.net Programming for Electronic Engineers - Elektor - ISBN

C# 2008 and.net Programming for Electronic Engineers - Elektor - ISBN Contents Contents 5 About the Author 12 Introduction 13 Conventions used in this book 14 1 The Visual Studio C# Environment 15 1.1 Introduction 15 1.2 Obtaining the C# software 15 1.3 The Visual Studio

More information

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain Duhok Polytechnic University Amedi Technical Institute/ IT Dept. By Halkawt Rajab Hussain 2016-04-02 String and files: String declaration and initialization. Strings and Char Arrays: Properties And Methods.

More information

Computer measurement and control

Computer measurement and control Computer measurement and control Instructors: András Magyarkuti, Zoltán Kovács-Krausz BME TTK, Department of Physics 2017/2018 spring semester Copyright 2008-2018 András Magyarkuti, Attila Geresdi, András

More information

C# Continued. Learning Objectives:

C# Continued. Learning Objectives: Learning Objectives: C# Continued Open File Dialog and Save File Dialog File Input/Output Importing Pictures from Files and saving Bitmaps Reading and Writing Text Files Try and Catch Working with Strings

More information

EEE-448 COMPUTER NETWORKS (Programming) Week -6 C# & IP Programming. The StringBuilder Class. StringBuilder Classes. StringBuilder with Append

EEE-448 COMPUTER NETWORKS (Programming) Week -6 C# & IP Programming. The StringBuilder Class. StringBuilder Classes. StringBuilder with Append EEE-448 COMPUTER NETWORKS (Programming) Week -6 C# & IP Programming Turgay IBRIKCI, PhD EEE448 Computer Networks Spring 2011 EEE448 Computer Networks Spring 2011 The StringBuilder Class The StringBuilder

More information

Chapter 14: Files and Streams

Chapter 14: Files and Streams Chapter 14: Files and Streams Files and the File and Directory Temporary storage Classes Usually called computer memory or random access memory (RAM) Variables use temporary storage Volatile Permanent

More information

Classes. System. class String // alias for string

Classes. System. class String // alias for string Classes System class String // alias for string Length char this [] operator string + (string, string) operator == (string, string) operator!= (string, string) static string Empty static Compare (string,

More information

Similarly, example of memory address of array and hash are: ARRAY(0x1a31d44) and HASH(0x80f6c6c) respectively.

Similarly, example of memory address of array and hash are: ARRAY(0x1a31d44) and HASH(0x80f6c6c) respectively. Lecture #9 What is reference? Perl Reference A Perl reference is a scalar value that holds the location of another value which could be scalar, arrays, hashes, or even a subroutine. In other words, a reference

More information

Console.ReadLine(); }//Main

Console.ReadLine(); }//Main IST 311 Lecture Notes Chapter 13 IO System using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks;

More information

Lecture # 7 Engr. Ali Javed 18th March, 2014

Lecture # 7 Engr. Ali Javed 18th March, 2014 Lecture # 7 Engr. Ali Javed 18 th March, 2014 Instructor s Information Instructor: Engr. Ali Javed Assistant Professor Department of Software Engineering U.E.T Taxila Email: ali.javed@uettaxila.edu.pk

More information

To start we will be using visual studio Start a new C# windows form application project and name it motivational quotes viewer

To start we will be using visual studio Start a new C# windows form application project and name it motivational quotes viewer C# Tutorial Create a Motivational Quotes Viewer Application in Visual Studio In this tutorial we will create a fun little application for Microsoft Windows using Visual Studio. You can use any version

More information

Type Description Example

Type Description Example Lecture #1 Introducing Visual C# Introduction to the C# Language and the.net Framework According to Microsoft, C# (pronounced C sharp ) is a programming language that is designed for building a variety

More information

accessmodifier [static] returntype functionname(parameters) { } private string getdatetime() { } public void getdatetime() { }

accessmodifier [static] returntype functionname(parameters) { } private string getdatetime() { } public void getdatetime() { } Lecture #6 User-defined functions User-Defined Functions and Delegates All C# programs must have a method called Main(), which is the starting point for the program. Programmers can also add other methods,

More information

Programming with Microsoft Visual Basic.NET. Array. What have we learnt in last lesson? What is Array?

Programming with Microsoft Visual Basic.NET. Array. What have we learnt in last lesson? What is Array? What have we learnt in last lesson? Programming with Microsoft Visual Basic.NET Using Toolbar in Windows Form. Using Tab Control to separate information into different tab page Storage hierarchy information

More information

CHAPTER 1: INTRODUCTION TO THE IDE 3

CHAPTER 1: INTRODUCTION TO THE IDE 3 INTRODUCTION xxvii PART I: IDE CHAPTER 1: INTRODUCTION TO THE IDE 3 Introducing the IDE 3 Different IDE Appearances 4 IDE Configurations 5 Projects and Solutions 6 Starting the IDE 6 Creating a Project

More information

CSCI 355 LAB #2 Spring 2004

CSCI 355 LAB #2 Spring 2004 CSCI 355 LAB #2 Spring 2004 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications

More information

C# Continued. Learning Objectives:

C# Continued. Learning Objectives: Learning Objectives: C# Continued Open File Dialog and Save File Dialog File Input/Output Importing Pictures from Files and saving Bitmaps Reading and Writing Text Files Try and Catch Working with Strings

More information

Advanced Programming Methods. Lecture 9 - Generics, Collections and IO operations in C#

Advanced Programming Methods. Lecture 9 - Generics, Collections and IO operations in C# Advanced Programming Methods Lecture 9 - Generics, Collections and IO operations in C# Content Language C#: 1. Generics 2. Collections 3. IO operations C# GENERICS C# s genericity mechanism, available

More information

ENGR 3950U / CSCI 3020U (Operating Systems) Simulated UNIX File System Project Instructor: Dr. Kamran Sartipi

ENGR 3950U / CSCI 3020U (Operating Systems) Simulated UNIX File System Project Instructor: Dr. Kamran Sartipi ENGR 3950U / CSCI 3020U (Operating Systems) Simulated UNIX File System Project Instructor: Dr. Kamran Sartipi Your project is to implement a simple file system using C language. The final version of your

More information

8 MANAGING SHARED FOLDERS & DATA

8 MANAGING SHARED FOLDERS & DATA MANAGING SHARED FOLDERS & DATA STORAGE.1 Introduction to Windows XP File Structure.1.1 File.1.2 Folder.1.3 Drives.2 Windows XP files and folders Sharing.2.1 Simple File Sharing.2.2 Levels of access to

More information

PrimoPDF User Guide, Version 5.0

PrimoPDF User Guide, Version 5.0 Table of Contents Getting Started... 3 Installing PrimoPDF... 3 Reference Links... 4 Uninstallation... 5 Creating PDF Documents... 5 PrimoPDF Document Settings... 6 PDF Creation Profiles... 6 Document

More information

Skinning Manual v1.0. Skinning Example

Skinning Manual v1.0. Skinning Example Skinning Manual v1.0 Introduction Centroid Skinning, available in CNC11 v3.15 r24+ for Mill and Lathe, allows developers to create their own front-end or skin for their application. Skinning allows developers

More information

// Precondition: None // Postcondition: The address' name has been set to the // specified value set;

// Precondition: None // Postcondition: The address' name has been set to the // specified value set; // File: Address.cs // This classes stores a typical US address consisting of name, // two address lines, city, state, and 5 digit zip code. using System; using System.Collections.Generic; using System.Linq;

More information

Programming Project 5: NYPD Motor Vehicle Collisions Analysis

Programming Project 5: NYPD Motor Vehicle Collisions Analysis : NYPD Motor Vehicle Collisions Analysis Due date: Dec. 7, 11:55PM EST. You may discuss any of the assignments with your classmates and tutors (or anyone else) but all work for all assignments must be

More information

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output. CSE 143 Java Streams Reading: 19.1, Appendix A.2 GREAT IDEAS IN COMPUTER SCIENCE REPRESENTATION VS. RENDERING 4/28/2002 (c) University of Washington 09-1 4/28/2002 (c) University of Washington 09-2 Topics

More information

Disk Operating System

Disk Operating System In the name of Allah Islamic University of Gaza Faculty of Engineering Computer Engineering Department Introduction To Computer Lab Lab # 1 Disk Operating System El-masry 2013 Objective To be familiar

More information

MATFOR In Visual C# ANCAD INCORPORATED. TEL: +886(2) FAX: +886(2)

MATFOR In Visual C# ANCAD INCORPORATED. TEL: +886(2) FAX: +886(2) Quick Start t t MATFOR In Visual C# ANCAD INCORPORATED TEL: +886(2) 8923-5411 FAX: +886(2) 2928-9364 support@ancad.com www.ancad.com 2 MATFOR QUICK START Information in this instruction manual is subject

More information

Simple FTP demo application using C#.Net 2.0

Simple FTP demo application using C#.Net 2.0 Стр. 1 из 5 Source : Mindcracker Network (www.c-sharpcorner.com) Print Simple FTP demo application using C#.Net 2.0 By Mohammed Habeeb January 18, 2007 An article to demonstrate common FTP functionalities

More information

Importing and Exporting Data

Importing and Exporting Data 14 Importing and Exporting Data SKILL SUMMARY Skills Exam Objective Objective Number Importing Data Import data into tables. Append records from external data. Import tables from other databases. Create

More information

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp Overview CSE 143 Topics Data representation bits and bytes Streams communicating with the outside world Basic Java files Other stream classes Streams Reading: Ch. 16 4/27/2004 (c) 2001-4, University of

More information

14.3 Handling files as binary files

14.3 Handling files as binary files 14.3 Handling files as binary files 469 14.3 Handling files as binary files Although all files on a computer s hard disk contain only bits, binary digits, we say that some files are text files while others

More information

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO) I/O and Scannar Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 I/O operations Three steps:

More information

C# Threading. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

C# Threading. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh C# Threading Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2018/19 0 Based on: "An Introduction to programming with

More information

For this example, we will set up a small program to display a picture menu for a fast food take-away shop.

For this example, we will set up a small program to display a picture menu for a fast food take-away shop. 146 Programming with C#.NET 9 Fast Food This program introduces the technique for uploading picture images to a C# program and storing them in a database table, in a similar way to text or numeric data.

More information

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE CSE 143 Overview Topics Data representation bits and bytes Streams communicating with the outside world Basic Java files Other stream classes Streams Reading: Ch. 16 10/20/2004 (c) 2001-4, University of

More information

Hands-On Lab. Instrumentation and Performance -.NET. Lab version: Last updated: December 3, 2010

Hands-On Lab. Instrumentation and Performance -.NET. Lab version: Last updated: December 3, 2010 Hands-On Lab Instrumentation and Performance -.NET Lab version: 1.0.0 Last updated: December 3, 2010 CONTENTS OVERVIEW 3 EXERCISE 1: INSTRUMENTATION USING PERFORMANCE COUNTERS. 5 Task 1 Adding a Class

More information

You can call the project anything you like I will be calling this one project slide show.

You can call the project anything you like I will be calling this one project slide show. C# Tutorial Load all images from a folder Slide Show In this tutorial we will see how to create a C# slide show where you load everything from a single folder and view them through a timer. This exercise

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

Preparatory steps before you begin

Preparatory steps before you begin Preparatory steps before you begin If the course comes on a CD-ROM / DVD-ROM If your course is on a CD-ROM, it might be easiest to copy its entire content, i.e., the folder containing the course, to your

More information

Topic 7: Algebraic Data Types

Topic 7: Algebraic Data Types Topic 7: Algebraic Data Types 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 5.5, 5.7, 5.8, 5.10, 5.11, 5.12, 5.14 14.4, 14.5, 14.6 14.9, 14.11,

More information

// Program 2 - Extra Credit // CIS // Spring // Due: 3/11/2015. // By: Andrew L. Wright. //Edited by : Ben Spalding

// Program 2 - Extra Credit // CIS // Spring // Due: 3/11/2015. // By: Andrew L. Wright. //Edited by : Ben Spalding // Program 2 - Extra Credit // CIS 200-01 // Spring 2015 // Due: 3/11/2015 // By: Andrew L. Wright //Edited by : Ben Spalding // File: Prog2Form.cs // This class creates the main GUI for Program 2. It

More information

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

CISC 323 (Week 9) Design of a Weather Program & Java File I/O CISC 323 (Week 9) Design of a Weather Program & Java File I/O Jeremy Bradbury Teaching Assistant March 8 & 10, 2004 bradbury@cs.queensu.ca Programming Project The next three assignments form a programming

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au Overview CSE 143 Topics Data representation bits and bytes Streams communicating with the outside world Basic Java files Other stream classes Streams Reading: Sec. 19.1, Appendix A2 11/2/2003 (c) 2001-3,

More information

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE Overview CSE 143 Topics Data representation bits and bytes Streams communicating with the outside world Basic Java files Other stream classes Streams Reading: Sec. 19.1, Appendix A2 11/2/2003 (c) 2001-3,

More information

Files.Kennesaw.Edu. Kennesaw State University Information Technology Services. Introduces. Presented by the ITS Technology Outreach Team

Files.Kennesaw.Edu. Kennesaw State University Information Technology Services. Introduces. Presented by the ITS Technology Outreach Team Kennesaw State University Information Technology Services Introduces Files.Kennesaw.Edu Presented by the ITS Technology Outreach Team Last Updated 08/12/13 Powered by Xythos Copyright 2006, Xythos Software

More information

ENGR/CS 101 CS Session Lecture 13

ENGR/CS 101 CS Session Lecture 13 ENGR/CS 101 CS Session Lecture 13 Log into Windows/ACENET (reboot if in Linux) Start Microsoft Visual Studio 2012 and open the Substitution Cipher Project Has everyone finished the program from last class

More information

Data Structures. 03 Streams & File I/O

Data Structures. 03 Streams & File I/O David Drohan Data Structures 03 Streams & File I/O JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.

More information

PrimoPDF Enterprise User Guide, Version 5.0

PrimoPDF Enterprise User Guide, Version 5.0 Table of Contents Installation... 3 Reference Links... 3 Uninstallation... 4 Creating PDF Documents... 4 PrimoPDF Document Settings... 5 PDF Creation Profiles... 5 Document Properties... 6 PDF Security...

More information

File System Interface: Overview. Objective. File Concept UNIT-IV FILE SYSTEMS

File System Interface: Overview. Objective. File Concept UNIT-IV FILE SYSTEMS UNIT-IV FILE SYSTEMS File System Interface: File Concept Access Methods Directory Structure File System Mounting Protection Overview For most users, the file system is the most visible aspect of an operating

More information

Senior Software Engineering Project CSSP Project CEN April 5, Adam Cox Tass Oscar

Senior Software Engineering Project CSSP Project CEN April 5, Adam Cox Tass Oscar Senior Software Engineering Project CSSP Project CEN 4935 April 5, 2006 Adam Cox Tass Oscar 1. Introduction One of the ways in which social worker professionals and students evaluate their clients is with

More information

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166 Lecture 22 Java Input/Output (I/O) Streams Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics I/O Streams Writing to a Stream Byte Streams Character Streams Line-Oriented I/O Buffered I/O

More information

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi CSE 143 Overview Topics Streams communicating with the outside world Basic Java files Other stream classes Streams Reading: Ch. 16 2/3/2005 (c) 2001-5, University of Washington 12-1 2/3/2005 (c) 2001-5,

More information

File. Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices

File. Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices Java I/O File Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices Magnetic disks Optical disks Magnetic tapes Sequential

More information

DATA STRUCTURE AND ALGORITHM USING PYTHON

DATA STRUCTURE AND ALGORITHM USING PYTHON DATA STRUCTURE AND ALGORITHM USING PYTHON Advanced Data Structure and File Manipulation Peter Lo Linear Structure Queue, Stack, Linked List and Tree 2 Queue A queue is a line of people or things waiting

More information

Course Hours

Course Hours Programming the.net Framework 4.0/4.5 with C# 5.0 Course 70240 40 Hours Microsoft's.NET Framework presents developers with unprecedented opportunities. From 'geoscalable' web applications to desktop and

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

CS112 Lecture: Streams

CS112 Lecture: Streams CS112 Lecture: Streams Objectives: Last Revised March 30, 2006 1. To introduce the abstract notion of a stream 2. To introduce the java File, Input/OutputStream, and Reader/Writer abstractions 3. To show

More information

Image Data Binding. Save images in database An image needs large amount of storage space. Only binary variable length fields may hold images.

Image Data Binding. Save images in database An image needs large amount of storage space. Only binary variable length fields may hold images. Image Data Binding Contents Save images in database... 1 Data Binding... 2 Update images... 3 Create method to select image into the Picture Box... 3 Execute SelectMethod when the Picture Box is clicked...

More information

using System; using System.Windows.Forms; public class Example { public static void Main() { if (5 > 3) { MessageBox.Show("Correct!

using System; using System.Windows.Forms; public class Example { public static void Main() { if (5 > 3) { MessageBox.Show(Correct! Lecture #4 Introduction The if statement C# Selection Statements A conditional statement (also known as selection statement) is used to decide whether to do something at a special point, or to decide between

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

The following is a simple if statement. A later lecture will discuss if structures in details.

The following is a simple if statement. A later lecture will discuss if structures in details. Lecture #2 Introduction What s in a C# source file? C# Programming Basics With the overview presented in the previous lecture, this lecture discusses the language core of C# to help students build a foundation

More information

As a first-time user, when you log in you won t have any files in your directory yet.

As a first-time user, when you log in you won t have any files in your directory yet. Welcome to Xythos WFS. This program allows you to share files with others over the Internet. When you store a file within your WFS account, you can make it selectively available to be viewed, edited, deleted,

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

CS 251 Intermediate Programming Java I/O Streams

CS 251 Intermediate Programming Java I/O Streams CS 251 Intermediate Programming Java I/O Streams Brooke Chenoweth University of New Mexico Spring 2018 Basic Input/Output I/O Streams mostly in java.io package File I/O mostly in java.nio.file package

More information

Fundamentals of Python: First Programs. Chapter 4: Strings and Text Files

Fundamentals of Python: First Programs. Chapter 4: Strings and Text Files Fundamentals of Python: First Programs Chapter 4: Strings and Text Files Objectives After completing this chapter, you will be able to Access individual characters in a string Retrieve a substring from

More information

Lab # 02. Basic Elements of C++ _ Part1

Lab # 02. Basic Elements of C++ _ Part1 Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special

More information

1.00/1.001 Tutorial 1

1.00/1.001 Tutorial 1 1.00/1.001 Tutorial 1 Introduction to 1.00 September 12 & 13, 2005 Outline Introductions Administrative Stuff Java Basics Eclipse practice PS1 practice Introductions Me Course TA You Name, nickname, major,

More information

Project 1 for CMPS 181: Implementing a Paged File Manager

Project 1 for CMPS 181: Implementing a Paged File Manager Project 1 for CMPS 181: Implementing a Paged File Manager Deadline: Sunday, April 23, 2017, 11:59 pm, on Canvas. Introduction In project 1, you will implement a very simple paged file (PF) manager. It

More information

Chapter 6 Dialogs. Creating a Dialog Style Form

Chapter 6 Dialogs. Creating a Dialog Style Form Chapter 6 Dialogs We all know the importance of dialogs in Windows applications. Dialogs using the.net FCL are very easy to implement if you already know how to use basic controls on forms. A dialog is

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Vanguide Application Set Installation Guide. Overview. Introduction

Vanguide Application Set Installation Guide. Overview. Introduction Vanguide Application Set Installation Guide Overview Introduction This guide explains how to: Install the Vanguide Application Set. Remove the Vanguide Application Set. How to unlock software images. This

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information