Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

C program called change1.c – writer.c -change2.c

Lab #2 – System Call I/O
Notes:
• You can only use system call open/close/read/write/lseek. No library I/O allowed.
• You may be given different text files for lab test. Those texts may include line
feed, tab, space, integer, string etc.
Part I.
Write a C program called writer.c. It uses system call I/O to create a file called
list1.txt which has the following text-based content:
101 GM Buick 2010
102 Ford Lincoln 2005
There are three blanks between the first and the second columns. There is one tab
between the second and third, and between the third and fourth columns.
You can only call function write once. After file list1.txt is created, type the following
commands to check the content of the file. Make sure you understand how
characters are internally saved.
>>>>> more list1.txt
>>>>> od –c list1.txt
>>>>> od –x list1.txt
Part II.
Write a C program called change1.c. Use system call I/O to open the file list1.txt, and
replace the string 101 with integer 101. After executing the program, type the
following commands to check the content of the file:
>>>>> more list1.txt # doesn’t work – not text-based!
>>>>> od –c list1.txt
>>>>> od –x list1.txt
Part III
Consider the car list where the first and second columns are swapped, with a tab
between them.
GM 101 Buick 2010

Ford 102 Lincoln 2005
Repeat Part I to create this text-based list2.txt. Use lseek() to write a program called
change2.c. Similar to Part II, it works on list2.txt to replace the string 101 with
integer 101. Check your result.

Answer:

PART 1

writer.c

#include <unistd.h>
#include <fcntl.h>
int main(){
	int fd;
	char A[44] =("101   GM\tBuick\t2010\n102   Ford\tLincoln\t2005\n");
	fd = open("list1.txt", O_WRONLY | O_CREAT | O_TRUNC,0755);
	write(fd, A, 44);
	close(fd);
}

PART 2

change1.c

#include <unistd.h>
#include <fcntl.h>
int main(){
	int fd;
	int A = 101; 
	fd = open("list1.txt", O_WRONLY, 0755);
	write(fd, &A, 3);
	close(fd);
}

PART 3

change2.c

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main(){

	int fd = open("list2.txt", O_WRONLY,0755);   
	lseek(fd,3,SEEK_SET);
	int n=101;
	write(fd,&n,4); 
	close(fd);
}

About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!