Reading array of complex numbers from file (.txt)

This is a discussion on Reading array of complex numbers from file (.txt) within the C Programming forums, part of the General Programming Boards category; Hello everyone, I have successfully WRITTEN an array of complex numbers into .txt file using fprintf and scanf(). However, I ...

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    10

    Reading array of complex numbers from file (.txt)

    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!!

    Joealem.

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

  2. #2
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Code:
                    fscanf(hFile, "???\t", &y????); 			
    
      fscanf(hFile,"%lf%lf",&re,&im);
      c = re + im * I;

  3. #3
    Registered User
    Join Date
    Dec 2010
    Posts
    10
    It works. Thank you so much!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 04:44 PM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 01:13 AM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 09:39 AM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21