OlveraeUNSW
返回题目列表
COMP1521

COMP1521 2020T3 Q5 · 文件I/O

COMP1521 2020T3 Q5 · 9 marks · C
知识点: 文件I/O(FILE) · 次: 文件大小/截断 · 难度: 中等
Topic: File I/O · Source: https://cgi.cse.unsw.edu.au/~cs1521/26T1/resources/practice_exams.html

一句话 / Summary: 复制文件但去掉末尾n字节


We need to a copy a file without some of the bytes at the end of the file.

Write a C program, 20t3final_q5.c which takes 3 arguments.

Its first argument will be an integer, n , the number of bytes not to be included.

Its second argument will be the name of an existing file.

Its third argument will be the name of the file to be created.

20t3final_q5.c should copy the bytes of the existing file to the new file
except for the last n bytes.

If the existing file has n bytes or less, the new files should still be created,
but with zero bytes.

For example:

dcc 20t3final_q5.c -o 20t3final_q5
echo hello >hello.txt
./20t3final_q5 2 hello.txt new.txt
ls -l hello.txt new.txt
-rw-r--r-- 1 z5555555 z5555555 6 Nov 26 16:28 hello.txt
-rw-r--r-- 1 z5555555 z5555555 4 Nov 26 16:29 new.txt
xxd hello.txt
00000000: 6865 6c6c 6f0a hello.
xxd new.txt
00000000: 6865 6c6c hell

Note new.txt has the same contents as hello.txt except it is 2 bytes shorter.

The last two bytes of hello.txt (ASCII 'o' and '\n' ) were
not copied to new.txt .

./20t3final_q5 2000 hello.txt file.txt
ls -l hello.txt file.txt
-rw-r--r-- 1 z5555555 z5555555 0 Nov 26 16:30 file.txt
-rw-r--r-- 1 z5555555 z5555555 6 Nov 26 16:28 hello.txt
xxd file.txt

There is no supplied code for this question.

No error checking is required.

Your program can assume it is always given 3 arguments.

Your program can assume its first argument is always a non-negative integer.

Your program can assume its second argument is always the pathname of an existing ordinary file.

Your program can assume its third argument is always the pathname of a file that can be created.

The file may contain any byte.

Your program should produce no output on stdout or stderr.

Your program should create a single file.

Your program should overwrite an existing file, if there is one.

Your program can assume all calculations can be done with int variables without overflow.

Your solution must be in C only.

You are not permitted to run external programs.
You are not permitted to use system, popen, posix_spawn, fork or exec.


🤖 Adapted for the online judge: write a C program with args <n> <infile>. Print to stdout the bytes of infile EXCEPT the last n bytes. If the file has ≤ n bytes, print nothing.

Fixture files are provided in the run workspace; reference outputs verified on the sandbox.

样例

stdin
期望输出
hell
stdin
期望输出
c-dcc
14