I want to make copy/paste with using c FILE but i need to add read/write buffer too and I am not sure how to add it. Is there any function similar to regular read/write..Code is below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]) {
FILE* fsource, * fdestination;
printf("enter the name of source file:\n");
char sourceName[20], destinationName[20];
strcpy(sourceName, argv[1]);
strcpy(destinationName, argv[2]);
fsource = fopen(sourceName, "r");
if (fsource == NULL)
printf("read file did not open\n");
else
printf("read file opened sucessfully!\n");
fdestination = fopen(destinationName, "w");
if (fdestination == NULL)
printf("write file did not open\n");
else
printf("write file opened sucessfully!\n");
char pen = fgets(fsource);
while (pen != EOF)
{
fputc(pen, fdestination);
pen = fgets(fsource);
}
fclose(fsource);
fclose(fdestination);
return 0;
}
Here's a reworking of your code (sans some error handling) that reads and writes in 256-byte increments:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *sourceName = argv[0];
char destName[256];
snprintf(destName, 256, "%s.copy", sourceName);
printf("Copying %s -> %s\n", sourceName, destName);
FILE *fsource = fopen(sourceName, "rb");
FILE *fdest = fopen(destName, "w");
char buffer[256];
for (;;) {
size_t bytesRead = fread(buffer, 1, 256, fsource);
if (bytesRead == 0) {
break;
}
if (fwrite(buffer, 1, bytesRead, fdest) != bytesRead) {
printf("Failed to write all bytes!");
break;
}
printf("Wrote %ld bytes, position now %ld\n", bytesRead, ftell(fdest));
}
fclose(fsource);
fclose(fdest);
return 0;
}
The output is e.g.
$ ./so64481514
Copying ./so64481514 -> ./so64481514.copy
Wrote 256 bytes, position now 256
Wrote 256 bytes, position now 512
Wrote 256 bytes, position now 768
Wrote 256 bytes, position now 1024
[...]
Wrote 168 bytes, position now 12968
Related
I wrote this little program that reads a file in binary form (Databases.db in this example) and copies its content in the cpydatabases.db...
When I run the debugger in the fopen_s(&source, "Databases.db", "r");, the source is always NULL (while debugging it shows that the memory entry is always Null, 0x000000000000 <NULL>).
This program runs in visual studio 2015.
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include "dirent.h"
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#define BUFFSIZE 2048
char ch, *readbuf;
int nread, nwrit;
FILE *source, *target;
int main()
{
int returnv;
fopen_s(&source, "Databases.db", "r");
if ( source !== NULL)
{
fclose(source);
return (EXIT_FAILURE);
}
fopen_s(&target,"cpydatabases.db", "w");
//check again
if (target == NULL)
{
fclose(target);
return(EXIT_FAILURE);
}
//setting the char that reads the binary
readbuf = (char *)malloc(BUFFSIZE* sizeof(char));
if (readbuf == NULL)
{
fclose(source);
fclose(target);
return(EXIT_FAILURE);
}
while (1)
{
nread = fread((void *)readbuf, sizeof(char), BUFFSIZE, source) ;
// fwrite((void *)readbuf, sizeof(char), nread, target);
nwrit = fwrite((void *)readbuf, sizeof(char), nread, target);
if (nwrit < nread)
{
returnv = (EXIT_FAILURE);
}
if (nread <= BUFFSIZE)
{
returnv = (EXIT_SUCCESS);
break;
}
}
fclose(source);
fclose(target);
return 0;
}
This worked for me. You should have your Databases.db file in the same folder as your source.cpp file, or use an absolute path like "C:/Databases". Anyway this code worked for me:
#define BUFFSIZE 2048
char ch, source_file[50], target_file[50], *readbuf;
int nread, nwrit;
FILE *source, *target;
int main()
{
int returnv;
fopen_s(&source, "Databases.db", "r");
if (source == NULL)
{
//fclose(source);
return (EXIT_FAILURE);
}
fopen_s(&target, "cpydatabases.db", "w");
//check again
if (target == NULL)
{
fclose(target);
return(EXIT_FAILURE);
}
I think "Databases.db" is in not in same directory where executable is.
You can give complete path of "Databases.db" or copy this file where your .sln file is.
I'm not good at C and I'm trying to do something simple. I want to open a binary file, read blocks of 1024 bytes of data and dump into a buffer, process the buffer, read another 1024 byes of data and keep doing this until EOF. I know how / what I want to do with the buffer, but it's the loop part and file I/O I keep getting stuck on.
PSEUDO code:
FILE *file;
unsigned char * buffer[1024];
fopen(myfile, "rb");
while (!EOF)
{
fread(buffer, 1024);
//do my processing with buffer;
//read next 1024 bytes in file, etc.... until end
}
fread() returns the number of bytes read. You can loop until that's 0.
FILE *file = NULL;
unsigned char buffer[1024]; // array of bytes, not pointers-to-bytes
size_t bytesRead = 0;
file = fopen(myfile, "rb");
if (file != NULL)
{
// read up to sizeof(buffer) bytes
while ((bytesRead = fread(buffer, 1, sizeof(buffer), file)) > 0)
{
// process bytesRead worth of data in buffer
}
}
#include <stdio.h>
#include <unistd.h> // For system calls write, read e close
#include <fcntl.h>
#define BUFFER_SIZE 1024
int main(int argc, char* argv[]) {
unsigned char buffer[BUFFER_SIZE] = {0};
ssize_t byte = 0;
int fd = open("example.txt", O_RDONLY);
while ((byte = read(fd, buffer, sizeof(buffer))) != 0) {
printf("%s", buffer);
memset(buffer, 0, BUFFER_SIZE);
}
close(fd);
return 0;
}
Edited code added
#include <stdio.h>
#include <unistd.h> // For system calls write, read e close
#include <fcntl.h>
#define BUFFER_SIZE 1024
int main(int argc, char* argv[]) {
unsigned char buffer[BUFFER_SIZE] = {0};
ssize_t byte = 0;
// open file in read mode
int fd = open("example.txt", O_RDONLY);
// file opening failure
if (fd == -1) {
printf("Failed to open file\n");
return -1;
}
// loop
while (1) {
// read buffer
byte = read(fd, buffer, sizeof(buffer));
// error
if (byte == -1) {
printf("Encountered an error\n");
break;
} else if (byte == 0) {
// file end exit loop
printf("File reading end\n");
break;
}
// printf file data
printf("%s", buffer);
memset(buffer, 0, BUFFER_SIZE);
}
// Close file
close(fd);
return 0;
}
While programming with files I stumbled upon some strange difference between the C library 'fread' function and the POSIX call 'read'; 'read' only reads a few bytes of a file while 'fread' reads the whole file.
This code only reads 1024 + 331 bytes, and then 'read' returns 0:
char buf[1024];
int id = open("file.ext", 0);
int len;
while((len = read(id, buf, 1024)) > 0)
println(len);
while this code reads the whole file as expected, around 11kb:
char buf[1024];
FILE* fp = fopen("file.ext", "rb");
int len;
while((len = fread(buf, 1, 1024, fp)) > 0)
println(len);
Can you tell why 'read' doesn't read the whole file?
EDIT2: I am sorry, I am using windows with MinGW, and reading a binary file
EDIT: A complete example:
#include <io.h>
#include <stdio.h>
int main() {
char buf[1024];
int len;
// loop 1
int id = open("file.ext", 0);
while((len = read(id, buf, 1024)) > 0) {
printf("%d\n", len);
}
close(id);
println("--------");
// loop 2
FILE* fp = fopen("file.ext", "rb");
while((len = fread(buf, 1, 1024, fp)) > 0) {
printf("%d\n", len);
}
fclose(fp);
while(1) {}
return 0;
}
The output:
1024
331
--------
1024
1024
1024
1024
1024
1024
1024
1024
1024
1024
981
You're opening the file the first time in text mode and the second time in binary mode. You need to open it both times in binary mode. If it's not in binary mode, the first control-z (hex value 1A) signals the "end of file".
Add the following includes (getting rid of <io.h>):
#include <unistd.h>
#include <fcntl.h>
The call open like this:
int id = open("spiderman.torrent", O_RDONLY|O_BINARY);
Here's an example of control-z ending the file:
#include <stdio.h>
void writeit() {
FILE *f = fopen("test.txt", "wb");
fprintf(f, "hello world\r\n");
fputc(0x1A, f);
fprintf(f, "goodbye universe\r\n");
fclose(f);
}
void readit() {
int c;
FILE *f = fopen("test.txt", "r");
while ((c = fgetc(f)) != EOF)
putchar(c);
fclose(f);
}
int main() {
writeit();
readit();
return 0;
}
The above only prints "hello world" and not "goodbye universe".
The question was updated...
The fread() loop is weird:
while ((len = fread(buf, 1, 1024, fp) > 0))
println(len);
Look at the parentheses — they're equivalent to:
while ((len = (fread(buf, 1, 1024, fp) > 0) ))
Now, fread() will return the number of bytes read, but the value assigned to len will be 0 or 1, so the printing from println() should repeat 1 a few times and then stop.
Is that you're actual code, or did you make a typing error in creating the question?
Compile and run this program (I called it rd compiled from rd.c):
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#define FILENAME "file.ext"
static void println(int val)
{
printf("%d\n", val);
}
int main(void)
{
char buf[1024];
int len;
int id = open(FILENAME, 0);
while ((len = read(id, buf, 1024)) > 0)
println(len);
close(id);
FILE *fp = fopen(FILENAME, "rb");
while ((len = fread(buf, 1, 1024, fp)) > 0)
println(len);
fclose(fp);
struct stat sb;
stat(FILENAME, &sb);
printf("Size: %d\n", (int)sb.st_size);
return 0;
}
Example output:
$ ls -l file.ext
-rw-r--r-- 1 jleffler staff 7305 Apr 6 08:08 file.ext
$ ./rd
1024
1024
1024
1024
1024
1024
1024
137
1024
1024
1024
1024
1024
1024
1024
137
Size: 7305
$
I have a problem at my C-lecture skill practice. My exercise is to read a text document (which is in the same directory like the program) char by char and write it reversed (so from the end to the beginning, char by char) at the Terminal (i have to work at Ubuntu).
Unfortunately it doesn't work - "read" only reads newline-chars (\n).
Can you find my mistake?
#include <sys/stat.h> //mode_t: accessing rights for the file
#include <fcntl.h> //for I/O
#include <unistd.h> //for file descriptors
#include <string.h> //for strlen
short const EXIT_FAILURE = 1;
short const EXIT_SUCCESS = 0;
char const* USAGE_CMD = "usage: write_file filename string_to_write\n";
char const* ERR_OPEN = "error in open\n";
char const* ERR_READ = "error in reading\n";
char const* ERR_CLOSE = "error in close\n";
char const* ERR_WRITE = "error in write\n";
int main(int argc, char** argv){
int fd = open(argv[1], O_RDONLY);
if(fd == -1){
write(STDERR_FILENO, ERR_OPEN, strlen(ERR_OPEN));
return EXIT_FAILURE;
}
int two_char_back = (-1)*sizeof(char); //shift-value for char
int one_back = -1; //shift-value for "no shift"
int length = lseek(fd, one_back, SEEK_END);//setting to one before oef
int i = 0; //for the loop
char buffer;
char* pbuffer = &buffer; //buffer for writing
while (i < length){
if (read(fd, pbuffer, sizeof(buffer)) == -1){ //READING
write(STDERR_FILENO, ERR_READ, strlen(ERR_READ));
return EXIT_FAILURE;
}
if(write(STDOUT_FILENO, pbuffer, sizeof(buffer)) == -1){ //WRITING
write(STDERR_FILENO, ERR_WRITE, strlen(ERR_WRITE));
return EXIT_FAILURE;
}
lseek(fd, two_char_back, SEEK_CUR); //STEPPING
i++;
}
if(close(fd) == -1){ //CLOSING
write(STDERR_FILENO, ERR_CLOSE, strlen(ERR_CLOSE));
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
This is wrong:
int two_char_back = (-1)*sizeof(char);
sizeof(char) is 1, you need -2
Haven't tried running it, but looks like two_char_back should be -2. The read advances the cursor, so -1 keeps reading the same one.
Also, just an option, you could make it more efficient by reading the whole file in then reversing it, then writing.
You have a typo in following line:
int two_char_back = (-1)*sizeof(char);
It must be:
int two_char_back = (-2)*sizeof(char);
As read() increments a cursor, you are actually reading the same character all the time e.g:
example text
^
|
After reading:
example text
^
|
After seeking:
example text
^
|
Thanks for your advices a lot!
& Thanks to my colleagues!
Now it works but I created kind of a new version, here it is:
#include <sys/stat.h> //mode_t: accessing rights for the file
#include <fcntl.h> //for I/O
#include <unistd.h> //for file descriptors
#include <string.h> //for strlen
short const EXIT_FAILURE = 1;
short const EXIT_SUCCESS = 0;
char const* USAGE_CMD = "usage: write_file filename string_to_write\n";
char const* ERR_OPEN = "error in open\n";
char const* ERR_READ = "error in reading\n";
char const* ERR_CLOSE = "error in close\n";
char const* ERR_WRITE = "error in write\n";
int main(int argc, char** argv){
int fd = open(argv[1], O_RDONLY); //OPENING
if(fd == -1){
write(STDERR_FILENO, ERR_OPEN, strlen(ERR_OPEN));
return EXIT_FAILURE;
}
int file_size = lseek(fd, 0, SEEK_END); //setting to eof
int i = file_size-1; //for the loop, runs from the end to the start
char buffer;
//the files runs from the end to the back
do{
i--;
lseek(fd, i, SEEK_SET); //STEPPING from the start
if (read(fd, &buffer, sizeof(buffer)) != sizeof(buffer)){ //READING
write(STDERR_FILENO, ERR_READ, strlen(ERR_READ));
return EXIT_FAILURE;
}
if(write(STDOUT_FILENO, &buffer, sizeof(buffer)) != sizeof(buffer)){ //WRITING
write(STDERR_FILENO, ERR_WRITE, strlen(ERR_WRITE));
return EXIT_FAILURE;
}
}while (i != 0);
buffer = '\n';
write(STDOUT_FILENO, &buffer, sizeof(buffer));//no error-det. due to fixed value
if(close(fd) == -1){ //CLOSING
write(STDERR_FILENO, ERR_CLOSE, strlen(ERR_CLOSE));
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
how can i use Regex Expressions in C programming?
for example if i want to find a line in a file
DAEMONS=(sysklogd network sshd !netfs !crond)
then print each daemon in separate line like this
sysklogd
network
sshd
!netfs
!crond
here what i did so far
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>
#define tofind "[a-z A-Z] $"
int main(){
FILE *fp;
char line[1024];
int retval = 0;
char address[256];
regex_t re;
if(regcomp(&re, tofind, REG_EXTENDED) != 0)
return;
fp = fopen("/etc/rc.conf","r");//this file has this line "DAEMONS=(sysklogd network sshd !netfs !crond)"
while((fgets(line, 1024, fp)) != NULL) {
if((retval = regexec(&re, address, 0, NULL, 0)) == 0)
printf("%s\n", address);
}
}
Any help would be much appreciated.
You read the line into line, so you should pass line to regexec(). You also need to think about whether the newline at the end of the line affects the patterns. (It was correct to use fgets(), but remember it keeps the newline at the end.)
You should also do return -1; (or any other value that is not 0 modulo 256) rather than a plain return with no value. Also, you should check that the file was opened; I had to use an alternative name because there is no such file as /etc/rc.conf on my machine - MacOS X.
This works for me:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <regex.h>
#define tofind "[a-z A-Z] $"
int main(int argc, char **argv)
{
FILE *fp;
char line[1024];
int retval = 0;
regex_t re;
//this file has this line "DAEMONS=(sysklogd network sshd !netfs !crond)"
const char *filename = "/etc/rc.conf";
if (argc > 1)
filename = argv[1];
if (regcomp(&re, tofind, REG_EXTENDED) != 0)
{
fprintf(stderr, "Failed to compile regex '%s'\n", tofind);
return EXIT_FAILURE;
}
fp = fopen(filename, "r");
if (fp == 0)
{
fprintf(stderr, "Failed to open file %s (%d: %s)\n",
filename, errno, strerror(errno));
return EXIT_FAILURE;
}
while ((fgets(line, 1024, fp)) != NULL)
{
line[strlen(line)-1] = '\0';
if ((retval = regexec(&re, line, 0, NULL, 0)) == 0)
printf("<<%s>>\n", line);
}
return EXIT_SUCCESS;
}
If you need help writing regular expressions instead of help writing C code that uses them, then we need to design the regex to match the line you show.
^DAEMONS=([^)]*) *$
This will match the line as long as it is written as shown. If you can have spaces between the 'S' and the '=' or between the '=' and the '(', then you need appropriate modifications. I've allowed for trailing blanks - people are often sloppy; but if they use trailing tabs, then the line won't be selected.
Once you've found the line, you have to split it into pieces. You might elect to use the 'capturing' brackets facility, or simply use strchr() to find the open bracket, and then a suitable technique for separating the daemon names - I'd avoid strtok() and probably use strspn() or strcspn() to find the words.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <regex.h>
#define tofind "^DAEMONS=\\(([^)]*)\\)[ \t]*$"
int main(int argc, char **argv)
{
FILE *fp;
char line[1024];
int retval = 0;
regex_t re;
regmatch_t rm[2];
//this file has this line "DAEMONS=(sysklogd network sshd !netfs !crond)"
const char *filename = "/etc/rc.conf";
if (argc > 1)
filename = argv[1];
if (regcomp(&re, tofind, REG_EXTENDED) != 0)
{
fprintf(stderr, "Failed to compile regex '%s'\n", tofind);
return EXIT_FAILURE;
}
fp = fopen(filename, "r");
if (fp == 0)
{
fprintf(stderr, "Failed to open file %s (%d: %s)\n", filename, errno, strerror(errno));
return EXIT_FAILURE;
}
while ((fgets(line, 1024, fp)) != NULL)
{
line[strlen(line)-1] = '\0';
if ((retval = regexec(&re, line, 2, rm, 0)) == 0)
{
printf("<<%s>>\n", line);
printf("Line: <<%.*s>>\n", (int)(rm[0].rm_eo - rm[0].rm_so), line + rm[0].rm_so);
printf("Text: <<%.*s>>\n", (int)(rm[1].rm_eo - rm[1].rm_so), line + rm[1].rm_so);
char *src = line + rm[1].rm_so;
char *end = line + rm[1].rm_eo;
while (src < end)
{
size_t len = strcspn(src, " ");
if (src + len > end)
len = end - src;
printf("Name: <<%.*s>>\n", (int)len, src);
src += len;
src += strspn(src, " ");
}
}
}
return EXIT_SUCCESS;
}
A good deal of debugging code in there - but it won't take you long to produce the answer you request. I get:
<<DAEMONS=(sysklogd network sshd !netfs !crond)>>
Line: <<DAEMONS=(sysklogd network sshd !netfs !crond)>>
Text: <<sysklogd network sshd !netfs !crond>>
Name: <<sysklogd>>
Name: <<network>>
Name: <<sshd>>
Name: <<!netfs>>
Name: <<!crond>>
Beware: when you want a backslash in a regex, you have to write two backslashes in the C source code.