UPI Study › Courses › Programming in C › Free lessons › Lesson 9.8 Free with a free account
Random Access File Operations in C
Programming in C · Chapter 9: String Manipulation via Pointers, File Streams, and File HandlingSection 9.8 · lesson 61 of 787 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Binary File I/O: fread() and fwrite() →← Structured Text File I/O: fprintf() and fscanf()Next lesson: Binary File I/O: fread() and fwrite() →
In this lesson
Moving the file cursor with fseek, ftell, and rewind.
- Explain how a file position counts bytes from zero and moves forward as you read
- Use fseek with SEEK_SET, SEEK_CUR, and SEEK_END, together with ftell and rewind
- Calculate where record n starts in a file of fixed-width records
- Check fseek and read results, and rename or remove files from a program
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (983 words). Read along, or search it.
Opening Question
Skipping Ahead Like a Music App
A cassette tape makes you wind through every song to reach track nine. A music app jumps straight there. Files in C can work like the app. If you know where a piece of data starts, you can leap to it, without reading everything before it. The Starlight Arcade keeps thousands of scores in one file, and Sam wants the three thousandth one, right now.
Core Idea
A File Is a Row of Numbered Bytes
So far, you've read files in order, from the first character to the last. That's sequential access, like reading a book from page one. But a file is really a long row of bytes, and every byte has a number. The first byte is number zero. This practice file holds the letters A to J, and a newline. Word count with dash c counts its bytes: eleven. For each open file, C keeps an invisible cursor: how many bytes it stands from the start. Reading a byte returns the byte at the cursor, then moves the cursor one step forward. Random access means you move the cursor yourself, to any spot, whenever you like.
Key Functions
Three Functions That Move the Cursor
Three functions move the cursor. Ftell asks: where is the cursor? It answers with a number of bytes, as a long. Rewind sends the cursor back to byte zero. And fseek moves it. It takes the file, an offset, which is how many bytes to move, and an origin, which says where to count from. SEEK SET counts from the start of the file. SEEK CUR counts from where the cursor is now, forward or back. SEEK END counts from the end. Fseek returns zero when the move worked, and something else when it didn't.
Worked Example
Tracing Each Cursor Jump
This program reads one letter after each move. Read one prints where the cursor was, just before the read. Build and run it. Two plain reads give A and B, and leave the cursor at two. Fseek, five, SEEK SET, jumps to byte five, so F comes next. Reading F leaves the cursor at six. So fseek, two, SEEK CUR, lands on eight, which is I. The file has eleven bytes, so minus two from SEEK END lands on nine, which is J. Byte ten is the newline. And rewind returns to A. It's the same as fseek to zero from SEEK SET, and it's how you read a file twice.
Quick Check
Four Bytes Back From the End
Quick check. Same letters file. This program moves four bytes back from the end, asks ftell where it is, then reads one character. What does it print? Pause and predict. Seven, H. The file is eleven bytes long, so the end is position eleven, and four back is seven. Byte seven is H, because A is byte zero. Six G is what you'd get by forgetting the newline. It's a byte too, and it counts.
Fixed-Width Records
Finding a Record by Multiplication
Here's the payoff. If every record in a file has the same length, you can work out where record n starts with one multiplication. This scores file gives each player a name padded with spaces to six characters, then a four-digit score, then a newline. That's six, plus four, plus one: eleven bytes per record. Five records make fifty-five bytes. So record n starts at byte n times eleven. Counting from zero, record three, Maya, starts at byte thirty-three. A file built this way has fixed-width records.
Worked Example
Jumping Straight to Any Record
Show record jumps straight there: fseek to n times the record length, from SEEK SET. Then fgets reads that one line. Main asks for records three, zero, four, and seven. Build and run it. The records come out in the order we asked for them, not the order they sit in the file. Record seven is past the end, so fgets returns NULL, and the program says so. Sam tried this on a board with three thousand scores. Reading from the top was slow. Jumping straight to the last player was instant. One warning: this math counts one byte per newline, which is true on Mac and Linux. Some systems store a text newline as two bytes. Binary mode, in nine point nine, avoids that.
Useful Trick
Measuring File Size With the Cursor
A neat trick: jump to the end with fseek, zero, SEEK END, then ask ftell. The cursor's number at the end is the number of bytes in the file. Build and run it. Fifty-five bytes. Divide by the record length, and there are five records, without reading a single line.
Common Mistake
Seeking Past the End Still Succeeds
Now a common mistake: trusting an fseek without looking at what it returned. This program tries two bad moves on the same fifty-five-byte file: five bytes before the start, and byte one thousand. Build and run it. Moving before the start is refused: fseek returns minus one. But moving past the end is allowed! Fseek returns zero, and ftell says one thousand. Only the read shows the truth: nothing is there. So check what fseek returns, and check your reads too.
File Management
Renaming and Removing Files
Last, files can be renamed from a program. Rename takes the old name and the new name, and returns zero when it worked. At the end of the day, Priya archives the board: scores dot text becomes scores underscore old dot text. A second call tries a file that doesn't exist. Build and run it. The first rename worked. The second failed, and perror gives the real reason. List the files starting with scores, and only the new name is left. Its partner, remove, deletes a file by name. And if the new name already exists, the standard leaves the result to the system. On this Mac, the file already using that name is replaced.
Key Takeaways
Cursor, Origins, and Record Math
To recap. A file is a row of bytes, numbered from zero, with a cursor that moves as you read. Fseek moves the cursor from SEEK SET, SEEK CUR, or SEEK END. Ftell reports it, and rewind returns to zero. With fixed-width records, record n starts at n times the record length. And check fseek's result: past the end is allowed, but nothing is there.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Random Access File Operations in C
What does fseek do in C?
How do you find the size of a file in C with fseek and ftell?
How do you jump to record n in a file with fixed-width records?
Can fseek move past the end of a file?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →