Hi I'm new here and I have a problem which is hindering me.

I have opened a file and wrote some stuff to it. Then later on I want to open the file and read it back in to a buffer. When I try to read the file back in to the buffer all it reads is the first line. I cannot understand why, also I cannot open the file I created in any text editor, they complain about the encoding.

Here is the code which writes to the file:

if((fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR))  == -1)
        printf("A file of the name \"%s\" exists or the file could not be created\n",filename);
	exit (5);
write(fd, seperator, strlen(seperator));
write(fd, "\n", 1);
write(fd, argv[2], strlen(argv[2]));
write(fd, "\n", 1);
write(fd, buffer, strlen(buffer));
write(fd, seperator, strlen(seperator));

Now if I cat out the file it has created it has exactly what I want in it, however gedit won't open it.

The following code is opening the file and attempting to write it to the buffer:

if((fd = open(argv[2], O_RDONLY)) == -1)
	printf("%s cannot be opened\n", argv[2]);
	exit (2);
eof = 0;
	status = read(fd,buffer,filesize);
	if (status == -1)
		printf("Error reading file %s\n", argv[2]);
		exit (4);
	else if (status == 0) 
		eof =  1;

Now if I print out the buffer it just contains the first line of the file and a few newlines. Any ideas?

BTW I am using Ubuntu 10.04


6 Years
Discussion Span
Last Post by Madawar

In the first case, i think the problem is with this:

sizeof("\n") = 2. not 1

because, "\n" is a string, and is terminated by a "\0".

write(fd, "\n", 1);

has to be

write(fd, "\n", 2);

i think this might fix it.


I dont have clear idea but write() function, may be it writes in binary mode so may be thats why text editors complaining ..


Instead of writing the "\n"'s I created a string which contained "\n" and wrote that instead. All works now cheers.


Use fread, fwrite functions they are in the standard C. In my Fedora when i create files with write i can,t also read them never researched why it doesn't work.


/*Code for writing and reading from file*/
#include <stdio.h>
#include <stdlib.h> 
#include <unistd.h>
    char sentence[100];
     char filename[100], fname[100];
     char c;
     int counter = 0;
     printf("Please enter file name \n");
     while ((c = getchar()) != '\n') {
         filename[counter] = c;
     filename[counter] = '\0';
     counter = 0;

     printf("Please enter sentence to be stored in file\n");
     while ((c = getchar()) != '\n') {
         sentence[counter] = c;
     sentence[counter] = '\0';

     FILE *in = fopen(filename, "w+");

     fputs(sentence, in);
     fread(fname, sizeof (fname), 1, in);
     printf("%s", fname);

This is guaranteed to work.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.