Two examples
char a[] = "Hello world!";
a[3] = 'z';It’s okay.
char *a = "Hello world!";
a[3] = 'z';It will drop. Tried to change string constant.
System Calls Input/Output
fscanf,freadand etc. uses integrated buffer
readandwritehas no buffer
Standard IO Streams
Use redirection
- Utils:
cat- file contenthead- file headerwc- count of lines, words, letters
- Generating IO streams:
ls -l > "dir.txt">- redirection parameter of stdout<- redirection parameter of stdin2>- redirection parameter of stderr
my_prog.out > "out.txt" 2> "err.txt" < "in.txt"How do we do it in C program?
int dup(int fd);- Returns first free descriptor. Its content equal to
fdcontent - Example:
- Returns first free descriptor. Its content equal to
fd = open();
close(0);
dup(fd);
read(0, ...);
close(fd);int dup2(int old_fd, int new_fd);- Returns first free descriptor.
old_fdline in FDT :=new_fdline.old_fdclose, if necessary- Example:
stdout_save = dup(1);
dup2(1, fd);
printf("i'm in fd!");
dup2(1, stdout_save);File Descriptor Table
fd = open();
| 0 | stdin |
|---|---|
| 1 | stdout |
| 2 | stderr |
| 3 | |
| … |
Open
int open(const char *path, int flags, mode_t mode)flags- access modes and etc.- Access modes:
O_RDONLY-rO_WRONLY-wO_APPEND-aO_RDWR-r+O_CREAT- create if not existsO_TRUNC- truncate file contentO_EXCLUDE- returns-1if file already exists (only with O_CREAT)
mode- access permissions for file- Returns file descriptor number or
-1in error case. - Example:
fd = open("my_file.dat", O_TRUNC|O_CREAT, 0664);
fopen -> FILE*.open -> int (file descriptor).
Read / Write
About regular files, but also we have:
- sockets
- channels
- devices files
int read(int fd, const void *buf, size_t size)- Returns count of read symbols or
-1in error case. - Example:
- Returns count of read symbols or
read(0, buf, 256);int write(int fd, void *buf, size_t size)- Returns count of written symbols or
-1in error case.
- Returns count of written symbols or
Seek
off_t lseek(int fd, off_f offset, int whence)whenceis start position. It has amount of constants:SEEK_SETSEEK_CURSEEK_END
- Examples:
lseek(fd, 0, SEEK_END);returns length of file
lseek(fd, 0, SEEK_CUR);Close
Terminal
int main() {
if() return 0;
else return 1;
}- Execution code:
gcc my_prog.c -o my_prog- `./my_prog
- `echo Hello
echo $?-> execution code
- Multiple commands:
&&- execute second if first was success||- execute allmkdir NewFolder && touch ./NewFolder/tst.txtvim ./NewFolder/tst.txt