Thread: writing randomly accessed files

  1. #1
    eh ya hoser, got a beer? stumon's Avatar
    Join Date
    Feb 2003
    Posts
    323

    writing randomly accessed files

    How would I be able to write information into a randomly accessed file using data stored in a struct? I am just trying to write a program that will create a file and store test data that will be used later. It seems to work when the user enters the input and I use fscanf with stdin and getting info for each member. Why won't it work when i just try to assign each member a specific value? The int seems to work, but the string is not. This is going to be a randomly accessed file so I can not use fprintf to load the test data because i will not be able to fseek it in a different program and use the struct size/byte locations as reference. If i comment out the string lines, it will compile and save the first set of according to size. I get 2 of the same errors (both are commented below).

    p.s. this is most of code, not all.

    Code:
    struct testinfo {
    	int checknum;
    	char payto[25];
    	double amount;
    	char description[35];
    };
    
    int main(void)
    {
    	FILE *filePtr;
    	struct testinfo info = {0, "", 0.0, ""};
    	int i;
    	
    	if ((filePtr = fopen("list.dat", "w")) == NULL)
    		printf("File could not be opened.\n");
    	else {
    		for (i = 0; i <= 100; i++)
    			fwrite(&info, sizeof(struct testinfo), 1, filePtr);
    
    		info.checknum = 100; 
    		info.payto = "Florida Power"; // '=' : left operand must be l-value
    		info.amount = 125.00; 
    		info.description = "Electricity"; // '=' : left operand must be l-value
    
    		fseek(filePtr, (info.checknum - 100) * sizeof(struct testinfo), SEEK_SET);
    		fwrite(&info, sizeof(struct testinfo), 1, filePtr);
    Thanks in advanced.

  2. #2
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Posts
    807
    and also for displaying error msgs like this:
    Code:
    printf("File could not be opened.\n");
    You should try using the perror() function.

  3. #3
    eh ya hoser, got a beer? stumon's Avatar
    Join Date
    Feb 2003
    Posts
    323
    Thanks a lot.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. writing files to a specified folder
    By jverkoey in forum Windows Programming
    Replies: 5
    Last Post: 03-29-2003, 11:09 PM
  2. *.COM Files? Writing them?
    By johnc in forum A Brief History of Cprogramming.com
    Replies: 13
    Last Post: 07-11-2002, 01:52 AM
  3. Making files, opening them, and writing to them
    By Unregistered in forum Game Programming
    Replies: 6
    Last Post: 06-18-2002, 09:57 PM
  4. Writing to files on exact spots
    By R@m0n in forum C++ Programming
    Replies: 3
    Last Post: 02-10-2002, 06:06 AM
  5. writing arrays to files
    By Zaarin in forum C++ Programming
    Replies: 1
    Last Post: 08-30-2001, 11:26 PM