FILE I/O: Low-level

  • Upload
    finian

  • View
    39

  • Download
    0

Embed Size (px)

DESCRIPTION

FILE I/O: Low-level. General Ideas. High vs. low-level Opening a file Closing a file Writing data to the file Reading data from the file (numerical, strings.. Etc ). 1. High vs low level. High level. Low level. Requires at least 3 lines! c lc c lear %open the file - PowerPoint PPT Presentation

Citation preview

4. LOW LEVEL FUNCTIONS

FILE I/O: Low-levelGeneral Ideas. High vs. low-levelOpening a fileClosing a fileWriting data to the fileReading data from the file (numerical, strings.. Etc)11. High vs low levelHigh level1 line of code opens the file, reads/write the data, closes the file

clcclear

%upload data from filedata = dlmread(myfile.dat);

%ready to analyze the data..Low levelRequires at least 3 lines!

clcclear

%open the file__ = fopen(_________);

%grab the data properly______(a lot of options)_____

%close the filefclose(_____);

%ready to analyze the data21. Low-Level, cont.Some files are mixed format that are not readable by high-level functions such as xlsread() and dlmread()!

Since the data is not easily recognized by any high-level function, every step to read the file requires a separate MATLAB command:Open a file, either to read-from or to write-toRead or write data from/to the file with the specific delimitersClose the file3

The order of today..first, learn the fopen() commandthen, learn the fclose() commanddump data to a file - fprintf()read string data - fgets() and fgetl()read numerical data -fscanf()read combination of numerical and string - textscan()42. Opening / Closing Files"Open a file"Program requests access to a file (from the OS) for reading and/or writing data to/from the file.

"Close a file"Inform the OS that the program is finished working with the file.52. Opening a fileThere are many syntaxes possible (from the doc file):

The most commonly used ones (in EGR115):

DescriptionfileID = fopen(filename); %opens the file filename for read access, and returns an integer file identifier.fileID = fopen(filename, permission); %opens the file with the specified permission.6

2. Opening a fileSyntax to open a filefileID = fopen( filename , permission );

fileID is known as a file identifier. It is like a "nickname" and is used instead of the filename when actually working with the file.

filename represents a string that is the name of the file with its extension (the letters after the dot). It can either be hardcoded, or within a variable

permission is a string that describes the type of access for the file>> why is this needed?72. Opening Files: permissionThe permission indicates how MATLAB will use the file after being opened.

Since the operating system has permissions (read-only, write-only) assigned to files, when you request access to a file you must tell the system in what mode you will be using the file.

The strings used for this tell the OS what it needs to know, and has an impact on how MATLAB will use the file.8

2. Opening Files: permissionThe most commonly used strings arerOpen file for reading (default).wOpen or create new file for writing. Discard existing contents, if any.aOpen or create new file for writing. Append data to the end of the file.

There are MANY more>> doc fopen 9

2. Opening Files: File Position PointerWhat happens when MATLAB opens a file to read or write?When a file is opened, a file position pointer is created. The system keeps track of the point in the file to which your program has read or written.

Think of it like a cursor that moves as you read or write the file.

The file position pointer is set initially to different locations depending on the permission granted.102. Opening Files: File Position PointerDepending on the access-mode, does a file get wiped or not, created or not? You should be able to reason this out memorization is not the key here!

Access Mode Delete Content? Create File?11rwaThis is the only tricky one. Think: w=write=wipe.2. Opening Files: Choosing a permissionTrivia

A log file is a file that keeps a history of events. Many programs keep log files. They help programmers see what occurred in the past so that a problem can be fixed.

For example, swiping for attendance creates a log-file.

If your program is going to keep a log file, what is the best mode to use when opening this file? Why?122. Closing FilesSyntax:fclose(fid); %usually ignore the return value

After working with a file, it is important to close the file. Other than being good form, it is critical when writing to the file.

Remember this? "Safe remove" warning on USB drives.When the OS is supposed to put information on disk it frequently waits until it determines the best time. This is known as "write caching".Windows may wait to write data. If your program finishes and Windows hasn't written this data, it will not be written at all!

>> Closing the file forces Windows to write the data to the disk.

13

2. Examples of opening and closing% Example 1) open a file from which to readfileGrades = fopen('grades.txt', 'r'); %hardcode the filename

%close filefclose(fileGrades);

% Example 2) ask user for a filename, then open it to readnameFile = input('Name of file with grades? (e.g. grades.txt): ', 's');fileGrades = fopen(nameFile, 'r');

%close filefclose(fileGrades);14Use the file handle not the file name!no quotes: a variableNotice that the file handle variable can be any acceptable variable name14Again, all the names in the template are dummies. Replace them by names that represent the content of the variable. For example, keywords like name or file or title are easy to remember.14Example:fh = fopen('log_file.txt', 'a');for k = 1:nbEvents fprintf(fh,'Event #%d: %15s %s\n',k,events{k,1},events{k,2});endfclose(fh);3. Writing to Text Filesfprintf(, The rest is as usual...);

Dont forget the semi-colon!Otherwise, MATLAB displays in the command window a number! fprintf() default output is how many characters were printed.15File handle not the file name!

3. MS Windows Text filesWhen writing to a text file, MATLAB will write only a single newline character to the end of a line.Yet, a Windows software (like Notepad) requires two different characters at the end of a line.

If you choose to open the file in a Windows based software, pad, it will not look like you expect:

But if you open with WordPad16

3. MS Windows Text filesThere is nothing wrong with this unless you intend to work with the file outside of your program (and in Windows).

To make it Windows-ready, write both a carriage return (\r) and a newline (\n):

17

3. Writing Text FilesInserting data into the middle of a text file

Writing to text files is not like working in Word!

When you write to a text file, the data added to the file will write over any existing data in the file after the files position pointer there is no insert mode!18

3. Writing Text Files19

What we think should happen3. Writing Text Files20

What REALLY happens

3. Writing Text FilesThere is no quick-fix to this problem.

You must write code that moves the existing file data so that you can insert the new data. This might mean copying to a new file, or looping and overwriting the old data.21

4. Reading text filesThere are many ways to read from a file, due to the infinite possibility of its content.Numbers? (Remember to use dlmread() if there is ONLY nbs!)Strings? Numbers and strings? Pattern? No pattern?

Therefore, there are many built-in functions, and ALL can be used in combinations, repeatedly, within a loop to make it work!22LAST but not least4. Reading filesExamples of files requiring low-level functions23

Its all about moving that cursor from top to bottom, and grabbing the data as you go!4. Reading text files - StringsReading an entire line as a string

including storing the new line character in the variablestr = fgets();

without storing the new line character in the variablestr = fgetl();

>> Both function calls above move the cursor down to the next line (you can use this to skip lines by ignoring its return value!)24Using fgets()Includes the new line character in your variable

25

Suppose we had this data file (.txt file)And ran this program:fh = fopen('testdata.txt', 'r');x = fgets(fh);fprintf(->%s%s