My C shell code is not working, could someone please fix it. It is supposed to r
ID: 3836920 • Letter: M
Question
My C shell code is not working, could someone please fix it.
It is supposed to read from a file 300 char and then write it to a different file, and do it as a loop (read another 300 char) until everything
is read and have been written into the other file.
I am using Linux shell, so if you fix it in another OS hopefully it will work for me too, but it needs checking, thanks.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
int fd1, fd2;
char c [301];
int r, w;
fd1 = open("/etc/passwd", O_RDONLY);
if (fd1 < 0) {
return -1;
}
fd2 = open("lab7taskoutput.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd2 < 0) {
printf("Unable to open out3.txt");
exit(1);
}
while(r > 0) {
r = read(fd1, c, 300);
w = write(fd2, c, r);
}
}
Explanation / Answer
Following is the program. I have used generic names that can be easily modified to the file name that you require.
=====================================================================================
Please provide your feedback if you find the solution helpful
===========================================
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
FILE *fd1, *fd2;
char file[100], c;
printf("Enter the filename to open for reading ");
scanf("%s", file);
// Open one file for reading
fd1 = fopen(file, "r");
if (fd1 == NULL)
{
printf("Unable to open %s ", file);
exit(0);
}
printf("Enter the filename to open for writing ");
scanf("%s", file);
// Open another file for writing
fd2 = fopen(file, "w");
if (fd2 == NULL)
{
printf("Cannot open file %s ", file);
exit(0);
}
// Read contents from file
c = fgetc(fd1);
while (c != EOF)
{
fputc(c, fd2);
c = fgetc(fd1);
}
printf(" Contents copied to %s", file);
fclose(fd1);
fclose(fd2);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.