Weird output from integer array to a file - c

Hi I am writing a program that generates random ints, put them in an array and save them to a file. Everything seems to work good but after I open this file it has this strange content : ^K^#^#^S^#^#^#^[^#
What have I done wrong?
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[]) {
int tab[10];
int fd;
srand(time(0));
int i;
for(i = 0; i < 10; i++)
tab[i] = rand() % 50;
if(argc != 2 || strcmp(argv[1], "--help") == 0)
{
.......
}
fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0644);
write(fd, tab, 10);
close(fd);
return 0;
}

The content is wierd because you're writing binary values, random character codes from 0 to 50. But the information is there all right (well, you have to write sizeof(int) times more data to store all the data though, and it can be corrupt on Window because you're missing O_BINARY and some carriage return chars may be inserted at some locations...):
fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0644); // add | O_BINARY if you use windows
write(fd, tab, 10 * sizeof(int)); // you can use (fd,tab,sizeof(tab)) too as it's an array, not a pointer
Use a hex editor you'll see the values (with a lot of zeroes since your values can be encoded in a byte). But not with a text editor.
If you want to write formatted integers as strings, use fopen and fprintf on the values, in a text file, not binary. Quick & dirty (and also untested :)):
FILE *f = fopen(argv[1], "w"); // #include <stdio.h> for this
if (f != NULL)
{
int i;
for (i = 0; i < 10; i++)
{
fprintf(f,"%d ",tab[i]);
}
fclose(f);
}

Related

C program reading and writing to binary files

Hello this is the first time I am working with binary file in C.
I am trying to first write the data to the file and then I to read the same data from the file. But somehow I am not reading the data correctly (that's what I think) because I think the file writing part has no issue. And I am doing all of this in unix.
So basically I am trying to write and read data from the binary file in unix and I am not able to read the data properly. Any help would be appreciated. Thanks in advance.
I have attached the code and the output below so it is understandable:
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char data[100];
if(argc<2){
printf("Usage: gift <textstring>\n");
return -1;
}
int n = 0;
int num = 0;
char data[100];
if(argc<2){
printf("Usage: gift <textstring>\n");
return -1;
}
int n = 0;
int num = 0;
int fd = open("gifts.dat", O_CREAT | O_WRONLY | O_RDONLY);
if((strcmp(argv[1],"new"))==0){
for(int i = 2; i < argc; i = i+2){
int number = atoi(argv[i+1]);
strcpy(data, argv[i]);
int length = strlen(data) + 1;
write(fd,&length, sizeof(int));
write(fd,data, length);
write(fd,&number, sizeof(int));
}
}
else{
printf("Not worked");
}
for(int k =0;k < ((argc-2)/2);k++){
int length;
char*name = NULL;
int money;
read(fd, &length, sizeof(int));
name = malloc(length);
read(fd, name, length);
read(fd, &money, sizeof(int));
printf("%10s: %.2f\n", name, money);
}
return 0;
}
And then here is the output of the binary file
gcc -o gifts board.c
./gifts new patel 200 Ram 500
: 0.00
: 0.00
od -c gifts.dat
0000000 006 \0 \0 \0 p a t e l \0 310 \0 \0 \0 004 \0
0000020 \0 \0 R a m \0 364 001 \0 \0 \0 \0
0000034
cat gifts.dat
patelÈRamô{cslinux1:~/CS3377_hmb180006}
Make sure to use alias gcc='gcc -std=c99'before compiling with gcc
The primary problem is with your open() call. You are attempting to open the file as both read-only and write-only at the same time. From man 2 open:
The argument flags must include one of the following access
modes: O_RDONLY, O_WRONLY, or O_RDWR.
Refactoring your code as follows works fine.
char data[100];
int fd = open ("gifts.dat", O_CREAT | O_WRONLY);
int n = 0;
if ((strcmp(argv[1],"new")) == 0) {
for (int i = 2; i < argc; i = i+2){
int number = atoi (argv[i+1]);
strcpy (data, argv[i]);
int length = strlen(data) + 1;
write (fd, &length, sizeof(int));
write (fd, data, length);
write (fd, &number, sizeof(int));
n++;
}
}
else{
printf("Not worked");
}
close (fd);
fd = open ("gifts.dat", O_CREAT | O_RDONLY);
for (int k = 0; k < n; k++){
int length;
char name[100];
int money;
read (fd, &length, sizeof(int));
read (fd, name, length);
read (fd, &money, sizeof(int));
printf("%10s: %.2d\n", name, money);
}
close (fd);
Example Use/Output
$ ./bin/readwrite_bin new patel 200 Ram 500
patel: 200
Ram: 500
Additionally, you must validate all opens, reads, writes (and close - after write) by checking the return of each call to ensure is succeeds, or handle any error if it fails. You should replace atoi() with at minimum sscanf() or better strtol() as atoi() provides zero error detection and will happily accept atoi ("my cow");
Let me know if you have further questions.

Reading a Binary File for Floats and Putting them into an Array

I am reading a binary file for floats and storing them in an array. There is a set of 4 byte floating-point values in the file. However, with my current code, the values of the last two indexes of the array are always read as the same value instead of what the actual value of the last index is.
For example, I am getting
array[0] = -123456.123456
array[1] = 123456.123456
array[2] = 123456.123456
when I should be getting something like
array[0] = -123456.123456
array[1] = 123456.123456
array[2] = 654321.654321
I am not sure what I am doing incorrectly in terms of the reading and why I am getting this output.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <float.h>
int main(int argc, char *argv[]) {
int fd;
float num;
size_t nr;
int elementnum = 0;
fd = open(argv[1], O_RDONLY);
nr = read(fd, &num, sizeof(float));
if (fd == -1){
printf("Error opening file");
exit(1);
}
if (nr == -1){
printf("Error reading file");
exit(1);
}
struct stat st;
fstat(fd, &st);
off_t size = st.st_size;
for (int j = 0; j < size/4; j++){
elementnum++;
}
printf("number of elements: %d\n", elementnum);
float array[elementnum];
for (int i = 0; i < elementnum; i++){
nr = read(fd, &num, sizeof(float));
array[i] = num;
}
for (int i = 0; i < elementnum; i++){
printf("Before Sorting: %f\n", array[i]);
}
close(fd);
return 0;
}
You need to check the value returned by each read. Since you read one byte out of the file right after you open it (apparently just to validate that one read works) and do not rewind, your loop is trying to read one more value than is available. If you check the read on the final iteration, I suspect you will see that it returns zero. Since it returns 0, it does not change the value of num, so num retains the value it had on the penultimate iteration.
IOW, stop reading a byte after you open. Instead, just open the file and check that open was successful. Then read until read returns 0 or -1. If read returns 0 before you expect it or if it returns -1, then print an error message.

I got strange characters to my file. I use unbuffered I/O stream in C language

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
int i, stream;
for (i = 20; i < 40; i++) {
if (i % 2 == 0) {
stream = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
char *x;
*x = i;
write(stream, &x, 1024);
close(stream);
}
}
return 0;
}
I got characters in file like:
#^#^#^#^#Z^#^#2#^#^#
There are multiple problems in the code.
One
char *x;
*x = i;
This creates a pointer which doesn't point anywhere, and immediately writes through that pointer. Undefined Behaviour. You probably wanted this:
char x = i;
Two
write(stream, &x, 1024);
This writes 1024 bytes starting from the address of the variable x. In the original case, x is a pointer, so it most likely occupies 4 or 8 bytes (depending on if your system is 32-bit or 64-bit, respectively). With the change I suggest above, x is a one-byte variable.
In either case, there are no 1024 bytes of data to write. You probably meant this:
int main(int argc, char* argv[]) {
int i, stream;
for (i = 20; i < 40; i++) {
if (i % 2 == 0) {
stream = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
char x = i;
write(stream, &x, 1);
close(stream);
}
}
return 0;
}

mmap is wiping my file instead of copying it

So I'm using mmap to then write to another file. But the weird thing is, when my code hits mmap, what it does is clears the file. So I have a file that's populated with random characters (AB, HAA, JAK, etc...). What it's supposed to do is use mmap as read basically and then write that file to the new file. So that first if (argc == 3) is the normal read and write, the second if (argc ==4) is supposed to use mmap. Does anyone have any idea why on Earth this is happening?
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/io.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/resource.h>
int main(int argc, char const *argv[])
{
int nbyte = 512;
char buffer[nbyte];
unsigned char *f;
int bytesRead = 0;
int size;
int totalBuffer;
struct stat s;
const char * file_name = argv[1];
int fd = open (argv[1], O_RDONLY);
int i = 0;
char c;
int fileInput = open(argv[1], O_RDONLY);
int fileOutPut = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
fstat(fileInput, &s);
size = s.st_size;
printf("%d\n", size);
if (argc == 3)
{
printf("size: %d\n", size);
printf("nbyte: %d\n", nbyte);
while (size - bytesRead >= nbyte)
{
read(fileInput, buffer, nbyte);
bytesRead += nbyte;
write(fileOutPut, buffer, nbyte);
}
read(fileInput, buffer, size - bytesRead);
write(fileOutPut, buffer, size - bytesRead);
}
else if (argc == 4)
{
int i = 0;
printf("4 arg\n");
f = (char *) mmap (0, size, PROT_READ, MAP_PRIVATE, fileInput, 0);
/* This is where it is being wipped */
}
close(fileInput);
close(fileOutPut);
int who = RUSAGE_SELF;
struct rusage usage;
int ret;
/* Get the status of the file and print some. Easy to do what "ls" does with fstat system call... */
int status = fstat (fd, & s);
printf("File Size: %d bytes\n",s.st_size);
printf("Number of Links: %d\n",s.st_nlink);
return 0;
}
EDIT: I wanted to mention that the first read and write works perfectly, it is only when you try to do it through the mmap.
If you mean it's clearing your destination file, then yes, that's exactly what your code will do.
It opens the destination with truncation and then, in your argc==4 section, you map the input file but do absolutely nothing to transfer the data to the output file.
You'll need a while loop of some description, similar to the one in the argc==3 case, but which writes the bytes in mapped memory to the fileOutput descriptor.

Problems with FILE Unbuffered I/O: Read and Write a String in C

I'm a student of computer science, to practice with Unbuffered I/O function, I tried to write some simple code in C. This code creates a file and then tries to write in this file one or more strings that we pass from the terminal. The output is not as expected. These are the commands that I write on the terminal.
gcc file_IO.c
./a.out file.txt hello world
cat file.txt
hello��*world2��
In "file.txt" there is only the string "hello". How can I print the string written to the file?
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[])
{
mode_t access_mode = S_IRUSR | S_IWUSR;
int flags = O_RDWR | O_CREAT | O_TRUNC;
int fd, i,n_char,index = 0;
char buffer[BUFFER_SIZE];
char buff_out[BUFFER_SIZE];
if( (fd = open(argv[1], flags, access_mode)) == -1 ){
perror("open");
exit(EXIT_FAILURE);
}
for(i = 2; i < argc; i++){
n_char = sprintf(buffer+index,"%s",argv[i]);
write(fd,buffer+index,sizeof(argv[i]) *4);
read(fd,buff_out,sizeof(argv[i]) * 4);
index += (strlen(argv[i]) +1);
}
if(( close(fd)) == -1 ){
perror("close");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
Thank you for all your assistance.
You are using sizeof to get the length of a string. That returns the size of a pointer (usually 4) not the length of the string. strlen should be used instead.
You are not checking the result of write and read. They can fail or can read/write only part of what you asked.
sprintf and read are not necessary to write the string to a file. Try:
for(i = 2; i < argc; i++){
write(fd, argv[i], strlen(argv[i]));
}
Notice that this still doesn't check return value from write.
You can't use sizeof to determine the length of a runtime string.
You also don't need to use snprintf at all. The string in argv can be written directly to the output file.
Try this instead:
write(fd,argv[i],strlen(argv[i]));
Also be aware that this won't output any spaces or newlines between the words.

Resources