• 0

[C] Loading a structure from a file, modify the structure, then save


Question

I have a local structure with several fields. I want to make this local structure be stored in a file. Everytime I load up the program it can either A: Create the file with the structure if it doesnt exist B: Load everything from the file into each structure's field. Then I work in the program modifying it, deleting it, etc etc. from the local structure then when I exit the program it has to save everything to the same file.

If someone needs code samples, Ill put them but please help me out as Im having problems opening/closing...

23 answers to this question

Recommended Posts

  • 0

I've actually tried this for some uni project, but I could never get it to work =/

If i still have a copy of the cource code somewhere, i'll post it here

---

You could post your code and I could try to get it to work, maybe it was different from mine

  • 0

I have

struct clients

{

int id;

char name[15];

char last[15];/

int number;

}c[num];

And I want to do the following:

I want to (this is seperte but related) control the information with a pointer.

And (this thread) insert id, name, last, number into the struct that at the begin and end of the program will load and save it from a clients.txt

And Im simply not sure how to do the second :) So if someone could help me out thanks.

OT: Is there any good and dedicated community with forums to programming, overall C?

  • 0
I have...

FILE *f=fopen(argv[1], "r");
list *l1; int i;
l1 = makelist(f);
fclose(f);

list *makelist(FILE *stream){
char letter;
int i = 0; int icount =0;
char word[30];
list *l1;
l1= NULL;
/*creates a new list and initialises it. While the character retrieved from//
the stream is not the end of the file,*/
while((letter=fgetc(stream))!=EOF){
/*initialises the character array to put the word on*/
for(icount=0; icount<30; icount++){
word[0] = '\0';
}
/*checks to see that the character is a letter*/
	if(((letter>64&&letter<91)||(letter>96&&letter<123)||letter==32)){
		if ((letter>64&&letter<91)||(letter>96&&letter<123)){
			while(letter!=EOF && (letter!=32) && (letter!='\0') && (letter!='\n')&& (letter!='.') && (letter!=',') && (letter!='\'')&&(letter!='"')&&(letter!=';')&&(letter!=':')&&(letter!=39)&&(letter!='!')&&(letter!='?')&&(letter!=39)&&(letter!=40)&&(letter!=41)&&(letter!=48)&&(letter!=49)&&(letter!=' ')&&(letter!='(')&&(letter!=')')){
				word[i] = letter;
				i++;
				letter=fgetc(stream);
		}
			/*adds an end marker on the end of the string*/
			word[i] = '\0';
			i = 0;
			/*makes the word uppercase*/
			for (i=0; i<strlen(word); i++){
				word[i] =toupper(word[i]);
			}
			i =0;
			/*places the word on the list*/
			l1 = insertlist(word, l1);

		}else{
			i= 0;
		}
	}	
}
/*returns the new list with the item added*/
return l1;
}

That's some code for reading to a list that I ripped from somtehing I did in my first year of uni :s.

As for writing... I did that somewhere too I'll look for a code fragment you could use.

Chris

[edit] Just read the if conditions; lol... what was going on there... I think there was an odd bug in it for a while, you can ignore most of them!!! [/edit]

  • 0

WOW :) You accually kind of help me out on another project!!!

I also have to write/read to graphs, lists, trees, and nodes. Thanks alot.

I understand all of the lines except why you use some of the variables and

while((letter=fgetc(stream))!=EOF){

What is fgetc exactly? (Something about a file and a character but...)

If you could help me out, or If i could add you to my Messenger if you dont mind, thank you very very VERY much :)

  • 0
I understand all of the lines except why you use some of the variables and

while((letter=fgetc(stream))!=EOF){

What is fgetc exactly? (Something about a file and a character but...)

I'm no expert with C but I'm pretty sure all that line does, is to look reading all characters from a stream until it encounters the EOF (End of File). fgetc just gets a character from a stream. More info here :)

  • 0
What exactly is a "stream"? I know its a noob question but...

You can think of a stream as a file. If you close the stream, you close the file. There are three special streams in C - stdin (standard input stream), stdout (standard output stream) and stderr (standard error output stream). Usually those are associated with the first three file handles:

stdin = file handle 0

stdout = file handle 1

stderr = file handle 2

  • 0

Chris's code didnt work :(

Let me explain again what IM trying to do

I have this (pseudocode):

stucture clients

name a string field

lastname a string field

age a integer field

find clients.txt and insert data from clients.txt into the clients stucture with name lastname and age

if clients.txt is not found create clients.txt and set all values as "0" in the clients structure

/* program */

/* end of program: */

collect data from strucuture clients and save all data in clients.txt

I hope that clears it up a bit :) All of this in C.

  • 0

Please someone....

I was playing around with fgets but I couldnt somehow get the function to read the file until the end of line (\o), insert into a field in the struct, then jump to the next line and insert into the next field in the struct.

  • 0

Sample C file:

#include <stdio.h>

struct client
{
  char name[15];
  char last[15];
  int age;
};

int main (void)
{
  struct client c; // a single client; make it an array for multiple clients, and remember to change the code accordingly
  FILE* client_file = fopen("clients.txt", "rt");

  /* file not found */
  if (!client_file)
	{
	  fputs("Warning: `clients.txt' was not found. Creating...", stderr);
	  client_file = fopen("clients.txt", "wt");
	  fputs("\t\t0", client_file); //assuming you are using a tab-delimited file for the fields; make sure to check the return value!!
	  fclose(client_file);
	  fputs("`clients.txt' created successfully", stderr);
	  return 1; //exit with a non-zero status (I made it positive because there wasn't an error)
	}

  /* file found */
  {
	char tmp = 0;
	for (unsigned int i = 0; (i < sizeof(c.name) - 1) || ((tmp != '\t') && (tmp != EOF)); ++i)
	  {
		tmp = fgetc(client_file);
		if ((tmp != '\t') && (tmp != EOF))
		  c.name[i] = tmp;
	  }
	c.name[sizeof(c.name) - 1] = 0;

	for (unsigned int i = 0; (i < sizeof(c.last) - 1) || ((tmp != '\t') && (tmp != EOF)); ++i)
	  {
		tmp = fgetc(client_file);
		if ((tmp != '\t') && (tmp != EOF))
		  c.last[i] = tmp;
	  }
	c.last[sizeof(c.last) - 1] = 0;

	while (((tmp = fgetc(client_file)) != '\n') && (tmp != EOF))
	  {
		c.age *= 10;
		c.age += tmp - 48;
	  }
  }

  fclose(client_file);

  return 0;
}

Sample `clients.txt' file:

Bob	Macquerel	82
George	Baeckermann	19
William	Corson		67

The sample C code would read the entry for "Bob Macquerel" and then close the file and exit, if that file existed, of course. It is untested, but it should work. Just remember to add proper error handling, and customize it to your needs.

Edit: Note that if the above sample `clients.txt' file has spaces between fields, they should be replaced by tabs. For example, "William<space><space><space>Corson<space><space>67" would become "William<tab>Corson<tab>67".

  • 0
Sample C file:

#include &lt;stdio.h&gt;

struct client
{
  char name[15];
  char last[15];
  int age;
};

int main (void)
{
  struct client c; // a single client; make it an array for multiple clients, and remember to change the code accordingly
  FILE* client_file = fopen("clients.txt", "rt");

  /* file not found */
  if (!client_file)
	{
	  fputs("Warning: `clients.txt' was not found. Creating...", stderr);
	  client_file = fopen("clients.txt", "wt");
	  fputs("\t\t0", client_file); //assuming you are using a tab-delimited file for the fields; make sure to check the return value!!
	  fclose(client_file);
	  fputs("`clients.txt' created successfully", stderr);
	  return 1; //exit with a non-zero status (I made it positive because there wasn't an error)
	}

  /* file found */
  {
	char tmp = 0;
	for (unsigned int i = 0; (i &lt; sizeof(c.name) - 1) || ((tmp != '\t') &amp;&amp; (tmp != EOF)); ++i)
	  {
		tmp = fgetc(client_file);
		if ((tmp != '\t') &amp;&amp; (tmp != EOF))
		  c.name[i] = tmp;
	  }
	c.name[sizeof(c.name) - 1] = 0;

	for (unsigned int i = 0; (i &lt; sizeof(c.last) - 1) || ((tmp != '\t') &amp;&amp; (tmp != EOF)); ++i)
	  {
		tmp = fgetc(client_file);
		if ((tmp != '\t') &amp;&amp; (tmp != EOF))
		  c.last[i] = tmp;
	  }
	c.last[sizeof(c.last) - 1] = 0;

	while (((tmp = fgetc(client_file)) != '\n') &amp;&amp; (tmp != EOF))
	  {
		c.age *= 10;
		c.age += tmp - 48;
	  }
  }

  fclose(client_file);

  return 0;
}

Sample `clients.txt' file:

Bob	Macquerel	82
George	Baeckermann	19
William	Corson		67

The sample C code would read the entry for "Bob Macquerel" and then close the file and exit, if that file existed, of course. It is untested, but it should work. Just remember to add proper error handling, and customize it to your needs.

Edit: Note that if the above sample `clients.txt' file has spaces between fields, they should be replaced by tabs. For example, "William<space><space><space>Corson<space><space>67" would become "William<tab>Corson<tab>67".

Thank you very much :) Ill test it out and post ASAP.

  • 0

Here is an example of reading a file and storing the contents in an array of structures. Then printing out the array. It should not be too difficult to adapt this to write to a file.

The expected file format is:

FirstName LastName Age
Bob Smith 32
Frank Furter 28

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

#define MAX_CLIENTS 100

typedef struct client
{
  char nfirst[20];
  char nlast[20];
  int age;
}client;

int main(void)
{
	client c[MAX_CLIENTS];
	char line[BUFSIZ];
	char* filename = "clients.txt";
	int read_cnt = 0, l_cnt = 1;
	int i = 0;

	FILE* fp = fopen(filename, "r");

	if(!fp) {
		printf("Failed to open file: %s\n", filename);
		exit(1);
	}

	/* read the file */
	while(fgets(line, sizeof(line), fp) &amp;&amp; read_cnt &lt; MAX_CLIENTS) {
		/* parse the line and save into client array */
		if(sscanf(line, "%19s %19s %d", c[read_cnt].nfirst, c[read_cnt].nlast, &amp;c[read_cnt].age) != 3) {
			printf("--line(%d) Bad line format--\n", l_cnt);
		}else{
			read_cnt++;
		}
		l_cnt++;
	}

	fclose(fp);

	/* print the list of clients to the screen */
	for(i = 0; i &lt; read_cnt; i++) {
		printf("%s %s %d\n", c[i].nfirst, c[i].nlast, c[i].age);
	}

	return 0;
}

  • 0
Here is an example of reading a file and storing the contents in an array of structures. Then printing out the array. It should not be too difficult to adapt this to write to a file.

The expected file format is:

FirstName LastName Age
Bob Smith 32
Frank Furter 28

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

#define MAX_CLIENTS 100

typedef struct client
{
  char nfirst[20];
  char nlast[20];
  int age;
}client;

int main(void)
{
	client c[MAX_CLIENTS];
	char line[BUFSIZ];
	char* filename = "clients.txt";
	int read_cnt = 0, l_cnt = 1;
	int i = 0;

	FILE* fp = fopen(filename, "r");

	if(!fp) {
		printf("Failed to open file: %s\n", filename);
		exit(1);
	}

	/* read the file */
	while(fgets(line, sizeof(line), fp) &amp;&amp; read_cnt &lt; MAX_CLIENTS) {
		/* parse the line and save into client array */
		if(sscanf(line, "%19s %19s %d", c[read_cnt].nfirst, c[read_cnt].nlast, &amp;c[read_cnt].age) != 3) {
			printf("--line(%d) Bad line format--\n", l_cnt);
		}else{
			read_cnt++;
		}
		l_cnt++;
	}

	fclose(fp);

	/* print the list of clients to the screen */
	for(i = 0; i &lt; read_cnt; i++) {
		printf("%s %s %d\n", c[i].nfirst, c[i].nlast, c[i].age);
	}

	return 0;
}

Great code; I understand it much better. Thank you very very much :)

My only 3 questions:

What is BUFSIZE (I know buffer size but whats it exactly mean)?

What is sscanf?

What is line?

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Microsoft Edge 149.0.4022.80 by Razvan Serea Microsoft Edge is a super fast and secure web browser from Microsoft. It works on almost any device, including PCs, iPhones and Androids. It keeps you safe online, protects your privacy, and lets you browse the web quickly. You can even use it on all your devices and keep your browsing history and favorites synced up. Built on the same technology as Chrome, Microsoft Edge has additional built-in features like Startup boost and Sleeping tabs, which boost your browsing experience with world class performance and speed that are optimized to work best with Windows. Microsoft Edge security and privacy features such as Microsoft Defender SmartScreen, Password Monitor, InPrivate search, and Kids Mode help keep you and your loved ones protected and secure online. Microsoft Edge has features to keep both you and your family protected. Enable content filters and access activity reports with your Microsoft Family Safety account and experience a kid-friendly web with Kids Mode. The new Microsoft Edge is now compatible with your favorite extensions, so it’s easy to personalize your browsing experience. Microsoft Edge 149.0.4022.80 changelog: Fixes Fixed an issue that prevented QR code generation from working. Feature updates Intune MAM Protected Downloads. The protected downloads feature for Intune MAM will now save downloaded files to the Documents > Microsoft Edge > Downloads folder in OneDrive. Extensions monitoring in the Edge management service. The Microsoft Edge management service now allows admins to gain visibility into extensions installed across their managed users. From the extensions monitoring page, admins can see which extensions have been installed as well as manage user requests for blocked extensions. For more information, see Microsoft Edge Extensions Monitoring. Validate Edge builds early with enterprise preview. Enterprise preview provides a simpler way for admins to flight pre-release Edge builds to their users. To reduce friction and bolster usage, users will receive pre-release builds directly inside of their Stable Edge application. Admins can allow users to easily opt-out of the preview experience, using built-in rollback to switch between their pre-release and stable channels with ease. Microsoft 365 admin center users can configure the feature, view their flighting population, and receive personalized recommendations all in one place. For more information, see Get started with Enterprise Preview in Microsoft Edge. Download: Microsoft Edge (64-bit) | 193.0 MB (Freeware) Download: Microsoft Edge (32-bit) | 170.0 MB Download: Microsoft Edge (ARM64) | 188.0 MB View: Microsoft Edge Website | Release History Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • The machines are starting to fight back any way they can.
    • No news articles about the Arch Linux repo being majorly infected with malware?!?
    • Waymo recalls self-driving software after cars enter closed freeway work zones by Paul Hill Waymo, the self-driving car maker owned by Alphabet – the parent company of Google –, has recalled some of its fifth-generation Automated Driving Systems (ADS). It did so after some of its cars drove through closed construction zones. According to the National Highway Traffic Safety Administration (NHTSA), the affected vehicles were capable of driving through a closed freeway construction zone and continuing to drive at speed. The listing on the NHTSA website says that Waymo is currently developing a solution to fix this issue, but in the meantime, freeway driving is being restricted. Waymo will update its ADS software so that vehicles can detect when they can avoid entering construction zones. According to the Safety Recall Report, on April 20, 2026, Waymo’s Field Safety Committee began meetings reviewing an event from April 11, 2026, and five events from April 19, 2026, where Waymo’s autonomous vehicles didn’t recognize and drove past ramp closure signs into the pre-planned freeway construction zones. This took place in Phoenix, Arizona. Separately, on May 18, 2026, seven Waymo vehicles entered freeway lanes with active construction in the San Francisco Bay Area by driving between cones that were placed to show the lane was closed. On the back of both of these events, Waymo restricted freeway driving until it could address the issue. In June, Waymo’s Safety Board reviewed the issue and additional information related to ADS performances around construction zones; then, as a result, it decided to conduct a recall. This development is not good for Waymo as it adds to a growing list of technical hiccups its cars have experienced. Ultimately, it will lead to more scrutiny from lawmakers around the world who will be more cautious about letting autonomous vehicles on their roads without tighter regulation. For readers in areas where Waymo operates, does this news make you more wary about stepping into one of these vehicles?
    • I'm still on Windows 10 22H2 because I didn't want to deal with all the issues in Windows 11, so I waited almost a week before installing the latest Patch Tuesday update (KB5094127), I went ahead and did it, and it was a huge mistake—ever since then, my File Explorer has seen a performance drop of about 30% when transferring large files... Once again, Microsoft has outdone itself! This update cannot be uninstalled, either through the Control Panel (via Settings) or by accessing Advanced Startup Options. The only possible alternative would be to use system restore points, but I’d have to reinstall all app and driver updates (and there’s no guarantee it would work). Or there’s the “nuclear option” of a in-place repair without losing files or apps, but even then, all my customizations would be lost! Microsoft just can’t help but mess everything up! Way to go, Microsoft! But I still don’t want your c****y Windows 11!
  • Recent Achievements

    • Week One Done
      Eurosoft10 earned a badge
      Week One Done
    • One Month Later
      Eurosoft10 earned a badge
      One Month Later
    • One Year In
      Skeet Campbell earned a badge
      One Year In
    • One Month Later
      Sharbel earned a badge
      One Month Later
    • First Post
      BizSAR earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      599
    2. 2
      +Edouard
      190
    3. 3
      PsYcHoKiLLa
      79
    4. 4
      Michael Scrip
      77
    5. 5
      Steven P.
      69
  • Tell a friend

    Love Neowin? Tell a friend!