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]));
	
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.