C read file in byte chunks [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Could not find proper documentation on this but I am trying to read a file using *nix system call read(). And I want read the file in 1024 byte chunks. Not sure what I have below is correct or not:
while (read(fd, buffer+i, 1024) == 1){
i++;
}
Can someone please verify?

Well if you can't use man, why not just search for it?
Anyway you are using it wrong. If you want to read it by chunks you should do it like this
// consider that we allocated enough memory for buffer
// and buffer is byte array
ssize_t r = 0, i = 0;
do {
r = read( fd, buffer + i, 1024 ); // try to read 1024 bytes
i += r;
} while( r > 0 );

Related

Read from stdin in the fastest way in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have to write a program in C in which I have to read some values from stdin and also to do it with the quickest function in C. The stdin is preloaded in a form like this:
int,int\n
char\n
int,int,int\n ex...
I'm asking for help because scanf is too slow for the time requirement of the project and also because I have some difficulties to read because of the ',' that I don't really need and that causes me problems.
I've tried with gets or getchar, but I didn't manage to make it work.
The fastest way to read stdin ("standard in" - 0 file descriptor) is to use read function from <unistd.h.>:
char buff[1024] = {0}; /* zero-initialize */
ssize_t res = read(0, &buff, sizeof(buff));
/* res is amount of bytes read; -1 if error */
Here is an example of program which reads 1024 bytes of stdin and echoes it to stdout (file descriptor: 1) (no error handling for simplicity):
#include <unistd.h>
#define BUFSIZ 1024
int main() {
char buff[BUFSIZ] = {0}; /* zero-initialize */
ssize_t nread = read(0, buff, BUFSIZ);
/* pass amount of bytes read as a byte amount to write */
write(1, buff, nread);
return 0;
}
This is the fastest way to read from stdin because read is native libc wrapper for a kernel syscall. By the way, you can use -O3, or even -Ofast compiler options to make it optimize the code.
Also, keep in mind that read and write are not guaranteed to read/write exactly as many bytes as you want, you should call it in a loop like this:
size_t to_write = sizeof(buff); /* example, can be result of read() */
int fd = 1;
size_t nwrote = 0;
while ((nwrote += write(1, buff, to_write) < to_write) {
/* pointer arithmetic to create offset from buff start */
write(fd, buff+nwrote, to_write - nwrote);
}

Reading from a fifo C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to read from a fifo and i am not understanding it's behaviour.
This is the write side, write.c:
for(int i = 1;i<argc;i++){
if(write(fifoFd,argv[i],strlen(argv[i])) <= 0)
perror("Error writing");
}
And this is the read side, read.c:
char buf[1024];
while(1){
int b = read(fifoFd,buf,1024);
if(b<=0) break;
}
printf("%s\n",buf);
First i start read.c ./read then i execute ./write
If i execute write like this ./write backup *.txt sometimes i get what i expected, i.e, backupexample1.txtexample2.txt.
But sometimes i only get example1.txtexample2.txt and i am not understanding this, where is "backup"?
Your code:
while(1){
int b = read(fifoFd,buf,1024);
if(b<=0) break;
}
printf("%s\n",buf);
You loop, each time through the loop you overwrite the buffer, and then you print the buffer. So, sometimes, you read "backup" followed by "example1.txtexample2.txt" (which overwrites "backup"), other times you read the whole lot at once in a single read.
If you change the loop to read into the unpopulated portion of the buffer, it will behave consistently:
int read = 0;
while(read != 1024){
int b = read(fifoFd,buf+read,1024-read);
if(b<=0) break;
read += b;
}
printf("%s\n",buf);

Reading file data without writing it to memory [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm writing a C code and, for some reason, the code I'm writing just needs to read without actually writing to a memory buffer. I can conveniently write data to a dummy local variable, but there must be unnecessary overheads caused by writing some variables to memory.
int rdsize = 0;
while (rdsize > SOME_BYTES) {
rdsize += fread (/* SOME BUFFER */, 1, SOME_BYTES - rdsize, file);
if (rdsize == -1) break;
}
In a word, I'd like to make the above code work without /* SOME BUFFER */. How can I do this? Close solutions are also greatly welcomed.
You can use fseek to skip an arbitrary number of bytes:
#include<stdio.h>
// Inside a function:
success = fseek(file, 1, SOME_BYTES - rdsize, SEEK_CUR);
if the purpose of your function is just to know the size of the file then you can use this function:
int filesize(FILE *file ){
int pos, size = -1;
pos = fseek( file, 0, SEEK_CUR); //save current position
if( pos != -1 ){
fseek(file, 0 , SEEK_END); // move to end
size = ftell(file); // get file size
fseek(file, pos, SEEK_SET); // rewind
}
return size;
}

How to access a .txt file from command-line input in C? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
For example, I run my program like:
program.exe < text.txt
I want the program to read from file text.txt. How do I begin doing this?
Ok, as this is a textfile, you probably want to read it line by line, so
char buf[1024];
while (fgets(buf, 1024, stdin))
{
/* do whatever you need with the line that's in buf here */
}
Note your code doesn't know about the file, it just reads from standard input. With <, you tell your environment (CMD on windows, a shell like e.g. bash on *nix) to open that file for you and provide it to your program as the standard input instead of the default, the controlling terminal, which would normally just read from the keyboard.
Hint: 1024 is kind of a random pick, most text files don't have lines exceeding 1kb. You might want to modify it to better suit your expected input.
another way to do what you are looking for is
#include <stdio.h>
int main (void) {
int c;
while ((c = fgetc(stdin)) != EOF) fputc(c, stdout);
return 0;
}
some more help here

How to write from all the file from child to parent using time? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have written the following code in c, the parent read what he get from child using pipe, and write it to a new file, and the child should wait between each 50 characters he read but the problem is that parent only write one line to the file, I know there is something missing but unable to recognize it?
if(fork())
{
//Parent
read(fd[0],str,sizeof(str));
fprintf(fpnew,str,"w+");
}
else
{
//Child 1
while(fgets(str,n,fp)!=NULL)
{
write(fd[1],str,sizeof(str));
sleep(1+rand()%10);
}
}
You need to put a loop in the parent to read the child output until it is finished. fprintf is the wrong thing to use here. If you want to stick to the std C lib then you probably want fwrite here. But rather than mix and match the stdlib functions with the lower level read I tend to like to be consistent. It's just one less thing to think about. You want something more like this. (Also, read up on the parameters of the functions you are using and check return code.)
int fpnew = open("whatever", O_WRONLY);
if (pfnew < 0)
error....
int bytesread;
while ((bytesread = read(fd[0], str, sizeof(str))) != 0)
write(fpnew, str, bytesread);
close(pfnew);

Resources