Solved

Open file append byte example code

Posted on 2007-12-06
25
1,198 Views
Last Modified: 2013-11-14
Hi, I am a C# developer, and I am starting to get interested in C. I am currently rewriting a C# app to C and I have been looking for some example code for a while now, and I have been unable to find anything that will help me. I really could use some example code that does the following, and I don't think it would take to long to write.

Open file.
Read last byte.
if byte is maxed (doesnt a single byte max at 255?)
-> Create new byte, append to file, save.
else
-> byte++, rewrite last byte, save.
print file to console

... I learn best by example, and a complete program that does this would teach me a lot, thank you.

Open in new window

0
Comment
Question by:addicktz
  • 14
  • 11
25 Comments
 
LVL 55

Accepted Solution

by:
Jaime Olivares earned 500 total points
Comment Utility
you nee something like:


void main()

{

    FILE *fp;

    unsigned char byte;
 

    fp = fopen("somefile.dat", "w+b");        /* open file in read/write binary mode */

    fseek(fp, -1, SEEK_END);  /* go to the end of the file */

    fread(&byte, 1, 1, fp);  /* read last byte */ 
 

    if (c==255)

    {

           fseek(fp, 0, SEEK_END);  /* just to append */

           byte = 0;   /* some value */

           fwrite(&byte, 1, 1, fp);   /* append byte */

    }

    else

   {

           fseek(fp, -1, SEEK_END);  /* just to overwrite last byte */

           byte++;   /* increment */

           fwrite(&byte, 1, 1, fp);   /* overwrite byte */

    }

}

Open in new window

0
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
forgot  fclose(fp) at the end of main(), also you will need this at the beginning of the code:

#include <studio.h>
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility
thats absolutely perfect, thank you so much, how can I use fprintf to display the contents of that file?
0
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
it is a binary file, how do you like to display this binary information?
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility
as text (ascii)
0
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
if you try to show as text directly you will have a lot of garbage on the screen.
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility
yes, I know this is an odd request, the fprintf of this example is actually for a different piece of code, i am just using this code to rewrite my code, im thinking its something like

???? fileContents = fread(???
fprintf(????, fileContents);
0
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
no, printf() won't work with binary streams, because a ascii-0 character will stop it.
you can use fwrite() to write to a file.
notice fprintf() will print to a file, printf() will print to the console, if you want to print to the console anyway you can use fwrite(some_buffer, some_size, 1, stdout).
stdout is a special handler that represents the console.
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility
ok awesome, thanks a lot, how would i read the contents of a file into a variable?
0
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
something like this:

    fread(&byte, 1, 1, fp);  /* read last byte */

1st argument: pointer to variable
2nd argument: size of variable (1 byte in this case)
3rd argument: element count (1, unless you are reading an array of elements)
4th argument: file handler
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility
so it would be something like

char contents;
fp = fopen("sometext.txt", "r");
fread(&contents,sizeOf(fp),sizeOf(fp),fp);
fprintf(stdout, contents);

?
0
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
sizeof(fp) won't give you the file size, if that is you are trying to do
if you specify char as the container variable, you should use sizeof(contents), which gives you 1
using sizeof() in the third argument won't work again

if you want to read all the entire contents of the file and then print, then you will need to:
open the file,
go to end of file with fseek()
use ftell() to know the file size
go to init of file with fseek()
dinamically allocate a memory portion with malloc() and get a pointer
read the file contents into the allocated memory()
close the file()
print all the contents using fwrite(), not fprintf()
deallocate the memory with free()

but this is a matter of other question...
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 1

Author Comment

by:addicktz
Comment Utility
ok awesome, thanks, im getting an error with this malloc....

        char contents;
      fp = fopen("somefile.dat", "r");
      fseek(fp, -1, SEEK_END);
      int somel = ftell(fp);
      fseek(fp, -1, SEEK_SET);  
      contents = malloc(somel);      
      fread(&contents,somel,somel,fp);
      fwrite(&contents,somel,somel,stdout);
      fclose(fp);

does this look right?
0
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
close, some mods:

  char contents;
      fp = fopen("somefile.dat", "rb");
      fseek(fp, -1, SEEK_END);
      int somel = ftell(fp);
      fseek(fp, 0, SEEK_SET);  
      contents = malloc(somel);      
      fread(&contents,somel,1,fp);    // dont read somel*somel bytes !!!
      fwrite(&contents,somel,1,stdout);
      fclose(fp);
      free(contents);  // free the allocation to avoid a leak
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility
amazing thank you =]
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility
hrmmm, i dont think byte==255 is working
0
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
in my code says:
   if (c==255)
 it should be:
   if (byte==255)
 
it should work, if not, try to test with printf("byte read=%i\r\n", (int)byte);
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility
ya its saying that byte == 8 everytime
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility



#include <stdio.h>
 

int main()

{

    FILE *fp;

    unsigned char byte;
 

    fp = fopen("somefile.dat", "w+b");        /* open file in read/write binary mode */

    fseek(fp, -1, SEEK_END);  /* go to the end of the file */

    fread(&byte, 1, 1, fp);  /* read last byte */
 

    printf("byte read=%i\r\n", (int)byte);
 

    if (byte==2)

    {

           fseek(fp, 0, SEEK_END);  /* just to append */

           byte = 0;   /* some value */

           fwrite(&byte, 1, 1, fp);   /* append byte */

    }

    else

    {

           fseek(fp, -1, SEEK_END);  /* just to overwrite last byte */

           byte++;   /* increment */

           fwrite(&byte, 1, 1, fp);   /* overwrite byte */

    }
 

    fflush(0);
 

    fclose(fp);
 

    return 0;

}

Open in new window

0
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
have you checked the real file contents? is it 08 the last byte in file?
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility
i havent, but I started the file over, and let the program create it, also, if 08 is the last byte in the file it should increment, but it keeps saying 8 everytime i run it, i just read on

http://visualcplus.blogspot.com/2006/02/lesson-6-ascii-code-and-character.html

that this should be working, if the fact is that it is an 8, is there something wrong to where its not over writing the last byte?
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility
also, I just changed the

byte == 2

to

byte == 8

and it didnt grow to two bytes...
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility
ok, i just added a printf after the byte increment, and it went to 9, so the original byte number is 8....why is the file not saving?
0
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
I think it is related with the file mode, change this line:
      fp = fopen("somefile.dat", "w+b");
to:
      fp = fopen("somefile.dat", "r+b");
 
0
 
LVL 1

Author Comment

by:addicktz
Comment Utility
will do, thanks again for your help
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
vcenter/esxi crash?  Going haywire... 18 202
Administrator Tools 2 65
Linux Hanging with disable Error Output 4 69
hp mini 3 13
The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
As the title indicates, I have done this before. It chills me everytime I update the OS on my phone, (http://www.experts-exchange.com/articles/18084/Upgrading-to-Android-5-0-Lollipop.html) because one time I did this and I essentially had a bricked …
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now