954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read/write complex arrays into/from Files

Hello everyone,

I have successfully WRITTEN an array of complex numbers into .txt file using fprintf and scanf(). However, I have no idea how to READ this file. Please see the attached code and reply with your suggestions.

Thank you in advance!!
Joelem

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<complex.h>

int main()
{


		
	_Complex double x[2][2],y[2][2];
	x[0][0]=1+1i;
	x[0][1]=1+2i;
        x[1][0]=2+1i;
	x[1][1]=2+2i;
	
	
	//Writing the above complex array into .txt file
	FILE *fp;
	
	fp=fopen("tdata.txt", "w");
	
	int j,k;
	for(j=0;j<2;j++)
	{
		for (k=0; k<2; k++) {
			fprintf(fp,"%g+%gi\t",creal(x[j][k]),cimag(x[j][k]));
						
		}
		fprintf(fp,"\n");
	}
	fclose(fp);
	
	
	
	
	//Reading the file from .txt file 
	FILE *hFile;
	hFile = fopen("tdata.txt", "r");
	
	
	if (hFile == NULL)
	{
		printf("FILE NOT FOUND\n");// Error, file not found
	}
	else
	{
		
	
		for(j=0;j<2; j++)
		{
			
			for (k=0;k<2;k++)
			{
				/// read from file and copy to y array
				
                fscanf(hFile, "???\t", &y????); 				
			}
			fprintf(hFile,"\n");
		}
		
	}
	fclose(hFile);
	 
	printf("\n y[0][0]=%g+%gi\n",creal(y[0][0]),cimag(y[0][0]));
	
}
joelem
Newbie Poster
1 post since Aug 2010
Reputation Points: 10
Solved Threads: 0
 

What formatting works with printf(), will work with fprintf(), and the formatting that works with scanf(), will also work with fscanf(), and sscanf(), etc.

Nearly all of the printf() formats, also work the same in scanf().

There are a LOT of formats for each of these. The right format for your program, depends on exactly how you want your numbers to be formatted.

Try man scanf in your Linux terminal, or fscanf formats in Google, or the help file in your C ide.

Adak
Nearly a Posting Virtuoso
1,479 posts since Jun 2008
Reputation Points: 425
Solved Threads: 185
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: