Read last 20 bytes from a file - c

int fd, read_byte;
char *c;
fd = open("foo.txt", O_RDONLY);
read_byte = read(fd, c, 20);
printf("");
How to read last 20 bytes from a file and print the read_byte to the screen.

Use lseek(2)
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main()
{
int fd, read_byte;
char c[21];
fd = open("foo.txt", O_RDONLY);
if (fd == -1) {
printf("Error opening file\n");
return -1;
}
// reposition fd to position `-20` from the end of file.
lseek(fd, -20L, SEEK_END);
read_byte = read(fd, c, 20); // Read 20 bytes
c[read_byte] = '\0';
printf("%s\n", c);
close(fd);
return 0;
}

Related

How to keep program unclosed after ctr+c in named pipe?

I have 2 programs.
One is server one is client. The Client sending string to the server, the server is swapping the string and return to the client.
the problems I have is when I pressing ctr+c the program(client) closed.(I'm using threads because I have been asking for.)
So how can I keep the program unclosed after ctr+c?
when clicking enter this is the right result and waiting for the server.
when entering ctl+c the program closed and cannot running server.c
The client.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#define MAX_BUF 1024
// client
int main()
{
int fd;
char *myfifo = "myfifo";
char str[MAX_BUF];
printf("Input string: ");
fgets(str, MAX_BUF, stdin);
str[strlen(str) - 1] = '\0';
if (mkfifo("myfifo", 0777) == -1)
{
if (errno != EEXIST)
{
printf("Could not create fifo file\n");
return 1;
}
}
/* create the FIFO (named pipe) */
fd = open(myfifo, O_WRONLY);
if (fd == -1)
return 2;
if (write(fd, str, MAX_BUF) == -1)
return 3;
close(fd);
fd = open(myfifo, O_RDONLY);
read(fd, str, MAX_BUF);
printf("%s\n", str);
/* remove the FIFO */
unlink(myfifo);
return 0;
}
The server
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#include <pthread.h>
#define MAX_BUF 1024
// server
// creatring struct for saving data
typedef struct thread_data
{
char str[MAX_BUF];
int result;
} thread_data;
// the
void *routine(void *arg)
{
int fd[2];
char *myfifo = "myfifo";
thread_data *tdata = (thread_data *)arg;
if (!(strcmp(tdata->str, "exit")))
tdata->result = 1; // is exit
else
tdata->result = 0; // not exit
if (tdata->result == 1)
{
fd[1] = open(myfifo, O_WRONLY);
write(fd[1], "Done", sizeof(MAX_BUF));
close(fd[1]);
}
else
{
char string[MAX_BUF] = {0};
char c = 0;
int length = 0, i = 0;
length = strlen(tdata->str);
printf("\nBefore Swap : %s\n", tdata->str);
for (i = 0; i < length / 2; i++)
{
c = tdata->str[i];
tdata->str[i] = tdata->str[length - 1 - i];
tdata->str[length - 1 - i] = c;
}
printf("\nAfter Swap String : %s\n", tdata->str);
fd[1] = open(myfifo, O_WRONLY);
write(fd[1], tdata->str, sizeof(MAX_BUF));
close(fd[1]);
}
pthread_exit(NULL);
}
int Calculation()
{
int fd[2];
// fd[0] read
// fd[1] write
char *myfifo = "myfifo";
char buf[MAX_BUF];
/* open, read, and display the message from the FIFO */
fd[0] = open(myfifo, O_RDONLY);
if(fd[0]==-1)
return 4;
if(read(fd[0], buf, MAX_BUF)==-1)
return 5;
close(fd[0]);
// res
int result;
thread_data tdata;
strcpy(tdata.str, buf);
pthread_t t1;
if (pthread_create(&t1, NULL, &routine, (void *)&tdata) != 0)
{
return 1;
}
if (pthread_join(t1, NULL) != 0)
{
return 2;
}
}
int main()
{
int res = Calculation();
return res;
}
To avoid closing a program you should capture and
manage the signal sent by CTRL + C, that is SIGINT, I have modified the code so that it captures the signal CTRL + C
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#define MAX_BUF 1024
// client
int main()
{
signal(SIGINT,SIG_IGN); // Register signal handler for ignoring the signal
int fd;
char *myfifo = "myfifo";
char str[MAX_BUF];
printf("Input string: ");
fgets(str, MAX_BUF, stdin);
str[strlen(str) - 1] = '\0';
if (mkfifo("myfifo", 0777) == -1)
{
if (errno != EEXIST)
{
printf("Could not create fifo file\n");
return 1;
}
}
/* create the FIFO (named pipe) */
fd = open(myfifo, O_WRONLY);
if (fd == -1)
return 2;
if (write(fd, str, MAX_BUF) == -1)
return 3;
close(fd);
fd = open(myfifo, O_RDONLY);
read(fd, str, MAX_BUF);
printf("%s\n", str);
/* remove the FIFO */
unlink(myfifo);
return 0;
}

Why is nothing printing from the text file?

I was trying out some exercises with the C language, specifically open() and read(). However, I've reached an impasse when I try printing to STDOUT the contents of a a text file (text.txt) that I have in the same directory as the c file. The size in bytes get printed, but the contents of the file do not.
I allocated space according to the size of the file, and added "1" for the null terminator. The manual page for read() states that it reads the contents of the file into the second parameter (void* buff). What am I missing/doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char* argv[]){
int fd = open("text.txt", O_RDONLY);
if (fd == -1){
printf("%s\n", strerror(errno));
return -1;
}
else {
int func = lseek(fd, 0, SEEK_END);
printf("%d bytes in size\n", func);
char* ptr = (char*)malloc(sizeof(char)*func + 1);
read(fd, ptr, func);
printf("%s", ptr);
free(ptr);
}
close(fd);
return 0;
}```
You need to move back to the beginning of the file before the read.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char* argv[]){
int fd = open("text.txt", O_RDONLY);
if (fd == -1){
printf("%s\n", strerror(errno));
return -1;
}
else {
int size = lseek(fd, 0, SEEK_END);
printf("%d bytes in size\n", size);
char* ptr = (char *) malloc(sizeof(char) * size + 1);
lseek(fd, 0, SEEK_SET); // move back to the beginning
read(fd, ptr, size);
printf("%.*s", size, ptr);
free(ptr);
}
close(fd);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char* argv[]){
int fd = open("text.txt", O_RDONLY);
if (fd == -1){
printf("%s\n", strerror(errno));
return -1;
}
else {
int size = lseek(fd, 0, SEEK_END);
printf("%d bytes in size\n", size);
char* ptr = (char *) malloc(sizeof(char) * size + 1);
lseek(fd, 0, SEEK_SET); // move back to the beginning
read(fd, ptr, size);
printf("%.*s", size, ptr);
free(ptr);
}
close(fd);
return 0;
}
(venv) [ttucker#zim stackoverflow]$ cat text.txt
asdf
qwer
sdfg
(venv) [ttucker#zim stackoverflow]$ gcc -o print print.c
(venv) [ttucker#zim stackoverflow]$ ./print
15 bytes in size
asdf
qwer
sdfg

Executable for the writer file with mkfifo halts

In my understanding, according to the https://linux.die.net/man/3/mkfifo,
I got an implication that I must have reader and writer file, in order to
utilize the pipe file. The source below is the writer file,
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <unistd.h>
int main(){
int fd;
char *myfifo = "./myfifo";
mkfifo(myfifo, 0777);
fd = open(myfifo, O_WRONLY);
int PID = fork();
if(PID == 0){
execl("./reader.o", "reader", (char*)NULL);
}
write(fd, "Rock and roll baby\0", sizeof("Rock and roll baby"));
close(fd);
unlink(myfifo);
return 0;
}
and the source being provided below is for the reader file.
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_BUF 1024
int main(){
int fd;
char* myfifo = "./myfifo";
char buf[MAX_BUF];
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
write(STDOUT_FILENO, buf, MAX_BUF);
close(fd);
exit(EXIT_SUCCESS);
return 0;
}
When run the executable for the writer file, the command prompt goes into
halt, after printing a newline. My assumption for this problem is because the
open() in the writer file is not being able to detect the pipe file,
is that the case?
Thank you.
I suggest that you should create the FIFO before the fork, but only open the FIFO after the fork. This avoids an assortment of problems. For the most part, I've used write() to report errors to standard error; it isn't as convenient as using fprintf(stderr, …) though.
Note that the writer writes a null byte at the end of the message. The reader gets the null byte, but overwrites it with a newline before writing the resulting character array (it is no longer a string; strings have a terminal null byte at the end) to standard output. If the code used <stdio.h> to write the data (e.g. printf("%s\n", buf)), it wouldn't need to replace the null byte with a newline.
writer.c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#ifndef READER
#define READER "./reader"
#endif
int main(void)
{
char *myfifo = "./myfifo";
if (mkfifo(myfifo, 0777) != 0)
{
write(STDERR_FILENO, "Failed to create FIFO\n",
sizeof("Failed to create FIFO\n") - 1);
}
int PID = fork();
if (PID == 0)
{
execl(READER, "reader", (char *)NULL);
write(STDERR_FILENO, "Failed to execute reader\n",
sizeof("Failed to execute reader\n") - 1);
exit(EXIT_FAILURE);
}
if (PID < 0)
{
write(STDERR_FILENO, "Failed to fork\n",
sizeof("Failed to fork\n") - 1);
exit(EXIT_FAILURE);
}
int fd = open(myfifo, O_WRONLY);
if (fd < 0)
{
write(STDERR_FILENO, "Failed to open FIFO for writing\n",
sizeof("Failed to open FIFO for writing\n") - 1);
unlink(myfifo);
exit(EXIT_FAILURE);
}
write(fd, "Rock and roll baby", sizeof("Rock and roll baby"));
close(fd);
unlink(myfifo);
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
printf("Child %d exited with status 0x%.4X\n", corpse, status);
return 0;
}
reader.c
#include <fcntl.h>
#include <unistd.h>
#define MAX_BUF 1024
int main(void)
{
char* myfifo = "./myfifo";
int fd = open(myfifo, O_RDONLY);
if (fd < 0)
write(STDERR_FILENO, "Failed to open FIFO for reading\n",
sizeof("Failed to open FIFO for reading\n")-1);
else
{
char buf[MAX_BUF];
int nbytes = read(fd, buf, MAX_BUF);
if (nbytes > 0)
{
buf[nbytes-1] = '\n';
write(STDOUT_FILENO, buf, nbytes);
}
close(fd);
}
return 0;
}
Example output
Rock and roll baby
Child 43734 exited with status 0x0000
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <unistd.h>
int main(){
int fd;
char *myfifo = "./myfifo";
int PID = fork();
if(PID == 0){
execl("./reader.o", "reader", (char*)NULL);
}
mkfifo(myfifo, 0777);
fd = open(myfifo, O_WRONLY);
write(fd, "Rock and roll baby\0", sizeof("Rock and roll baby"));
close(fd);
unlink(myfifo);
return 0;
}
After having the body of the code, where the execl is, moved above the
mkfifo(),
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_BUF 1024
int main(){
sleep(3);
int fd;
char* myfifo = "./myfifo";
char buf[MAX_BUF];
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
write(STDOUT_FILENO, buf, MAX_BUF);
close(fd);
exit(EXIT_SUCCESS);
return 0;
}
and having the reader have sleep() for 3 seconds, the programs started to
work; however, does anyone know if the two programs can open() the pipe file
exactly at the same time?
Thank you.

Reading and searching files using systemcalls in C

I tried reading from the file "hello.txt" but it doesn't enter the while loop at all. The read function returns 0 on EOF and -1 on error. I'm trying to search for the word in w if it exists in the file or not. I'm reading characters from the file and comparing them to w[].
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd;
char c;
int i=0;
int bytesread;
int flag=1;
char w[]={'h','e','l','l','o'};
if((fd=open("hello.txt",O_RDONLY,0))!=-1){ //if 1
bytesread = read(fd,&c,0);
if(bytesread!=-1){ //if 2
while(bytesread!=0)
{ //while
if(c==w[i])
{ //if 3
i++;
flag=0;
} //end of f3
else if(flag==0&&i!=0)
{ // else 3
i=0;
flag=1;
} // end of else 3
bytesread = read(fd,&c,0);
} //end of while
}else //end of if 2
printf("couldn't read file.\n");
}else //end of if 1
printf("Couldn't open file for read.\n");
} //end of main
ssize_t read(int fd, void *buf, size_t count);
read reads count bytes from the file. You're asking it to read zero bytes when doing bytesread = read(fd,&c,0);. Change it to bytesread = read(fd,&c,1);
Try this:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void)
{
int fd;
char c;
int bytesread;
if ((fd = open("hello.txt", O_RDONLY, 0)) != -1) {
while ((bytesread = read(fd, &c, 1)) == 1)
printf("read %d bytes [%c]\n", bytesread, c);
} else
printf("Couldn't open file for read.\n");
return 0;
}
read(fd,&c,0) asks the system to read zero bytes, and it shouldn't be what you want to do.
You should ask the system to read one byte by read(fd,&c,1).

How to send a file through a named pipe in C?

I have two programs, server and client. Server should read a file and then send its content through a named pipe to client. But my server reads only two chars from file, and then exits. What is wrong with this code?
server.c:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define FIFO_NAME "american_maid"
int main(void)
{
char line[300];
int num, fd;
FILE *fp;
fp = fopen("out.txt","r");
mknod(FIFO_NAME, S_IFIFO | 0666, 0);
printf("waiting for readers...\n");
fd = open(FIFO_NAME, O_WRONLY);
printf("got a reader--type some stuff\n");
while (fgets(line, sizeof(line), fp)) {
if ((num = write(fd, line, strlen(line))) == -1)
perror("write");
else
printf("speak: wrote %d bytes\n", num);
}
fclose(fp);
return 0;
}
client.c:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define FIFO_NAME "american_maid"
int main(void)
{
char s[300];
int num, fd;
mknod(FIFO_NAME, S_IFIFO | 0666, 0);
printf("waiting for writers...\n");
fd = open(FIFO_NAME, O_RDONLY);
printf("got a writer\n");
do {
if ((num = read(fd, s, 300)) == -1)
perror("read");
else {
s[num] = '\0';
printf("tick: read %d bytes: \"%s\"\n", num, s);
}
} while (num > 0);
return 0;
}
When I run the code shown below using the command sequence:
$ ln -s server.c out.txt
$ ./client &
$ ./server
$
I get a copy of the source code printed by the client program. Similarly when I run the commands using:
$ ./server &
$ ./client
$
The revised code is not modified all that significantly. It avoids do { } while(...) loops — they're so seldom really beneficial — and is very careful about not overflowing buffers. The code also has superfluous headers removed.
server.c
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define FIFO_NAME "american_maid"
int main(void)
{
const char infile[] = "out.txt";
FILE *fp = fopen(infile, "r");
if (fp == 0)
{
fprintf(stderr, "Failed to open %s for reading", infile);
return(1);
}
mknod(FIFO_NAME, S_IFIFO | 0666, 0);
printf("waiting for readers...\n");
int fd = open(FIFO_NAME, O_WRONLY);
if (fd > 0)
{
char line[300];
printf("got a reader--type some stuff\n");
while (fgets(line, sizeof(line), fp))
{
int len = strlen(line);
int num = write(fd, line, len);
if (num != len)
perror("write");
else
printf("speak: wrote %d bytes\n", num);
}
close(fd);
}
fclose(fp);
return 0;
}
client.c
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#define FIFO_NAME "american_maid"
int main(void)
{
const char outfile[] = "client.out";
FILE *fp = fopen(outfile, "w");
if (fp == 0)
{
fprintf(stderr, "Failed to open %s for writing\n", outfile);
return 1;
}
printf("waiting for writers...\n");
mknod(FIFO_NAME, S_IFIFO | 0666, 0);
int fd = open(FIFO_NAME, O_RDONLY);
if (fd > 0)
{
int num;
char s[300];
printf("got a writer\n");
while ((num = read(fd, s, sizeof(s))) > 0)
{
printf("tick: read %d bytes: \"%.*s\"\n", num, num, s);
fprintf(fp, "%.*s", num, s);
}
close(fd);
}
fclose(fp);
return 0;
}
Note that this version writes its output to file client.out; even when given a file with some very long lines to process (2049 bytes including the newline at the end), the output in client.out exactly matches the input in out.txt.
Remove the line mknod(FIFO_NAME, S_IFIFO | 0666, 0); from the file client.c. Then the program will work as expected. Server will create a file and sent the content of the file to fifo.

Resources