Random Access File Operations in C | Programming in C

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

← Structured Text File I/O: fprintf() and fscanf()Next lesson: Binary File I/O: fread() and fwrite() →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
fseek moves a stream's file position so the next read or write happens at a chosen byte. It takes the stream, a long offset, and an origin: SEEK_SET counts from the start of the file, SEEK_CUR from the current position, and SEEK_END from the end. It returns 0 when the move works and a nonzero value when it fails, so the result should be checked.
How do you find the size of a file in C with fseek and ftell?
Seek to the end with fseek(fp, 0, SEEK_END), then call ftell(fp). On Mac and Linux, the position it reports is the number of bytes in the file. A file of five 11-byte records, for example, reports 55, and dividing by the record length gives 5 records without reading a single line. Call rewind(fp) afterward to read from the start again.
How do you jump to record n in a file with fixed-width records?
Multiply the record number by the record length and seek there from the start: fseek(fp, n * RECLEN, SEEK_SET). Records count from zero. If each record holds a 6-character name, a 4-digit score, and a newline, it is 11 bytes long, so record 3 starts at byte 33. One fgets call then reads just that record.
Can fseek move past the end of a file?
Yes. On Mac and Linux, seeking past the end is allowed, and fseek returns 0 even though no data exists there. ftell then reports the new position, such as 1000, but the next read finds nothing and fgets returns NULL. Seeking before the start is different: fseek refuses and returns a nonzero value. Checking both the fseek result and every read catches these cases.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

Programming in C
3 credits · NCCRS
Enroll →