Created
August 28, 2017 05:02
-
-
Save ashutoshbsathe/648ebb2d7c8655f192bf0c8b05258492 to your computer and use it in GitHub Desktop.
Reference code for the DSA Discussion Forum on Moodle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
int main() { | |
int fd1, fd2; | |
char a[16] = "ABCDEFGHIJKLMNOP", ch; | |
fd1 = open("test1", O_RDWR | O_CREAT, 0666); | |
write(fd1, a, sizeof(a)); | |
close(fd1); //closing and opening fd1 will reset the file handle to start of the file | |
fd1 = open("test1", O_RDWR, 0666); | |
// Now create a new file in which you will store new data. | |
fd2 = open("test2", O_RDWR | O_CREAT | O_TRUNC, 0666); | |
while(read(fd1, &ch, sizeof(char))) { | |
switch(ch) { | |
case 'D' : | |
case 'E' : | |
case 'F' : | |
case 'G' : break; | |
default : write(fd2, &ch, sizeof(char)); | |
} | |
} | |
close(fd2); | |
//Now we have to delete test1 and rename test2 to test1 | |
fd1 = open("test1", O_RDWR | O_CREAT | O_TRUNC, 0666); | |
fd2 = open("test2", O_RDWR, 0666); | |
while(read(fd2, &ch, sizeof(char))) | |
write(fd1, &ch, sizeof(char)); | |
//Copying ends here. | |
//Now we need to delete test2 | |
close(fd2); | |
fd2 = open("test2", O_RDWR | O_TRUNC, 0666); | |
close(fd2); | |
close(fd1); | |
return 0; | |
} | |
/* The only drawback of this method is that , it will also create an empty file called test2 along with modified test1. | |
* If anyone finds a way to work around this using only read(), write(), open() and close() please let me know | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment