C/C++ : SEGY Merge

C/C++ : SEGY Merge

In my last post, I am create a method how to merge SEGY with cat and dd command. Now, I am create a C/C++ SEGY merge code. This is the main C/C++ : SEGY Merge code :

void usage()
{
	printf("\nSEGY_MERGE \n");
	printf("by toto (toto-share.com)\n\n");
	printf("segy_merge segy1 segy2 segy3 ... segyn > output.sgy \n");
	printf("\n");
}

int main(int argc, char **argv)
{
	int i, j, result;
	int ns, dt, format, nsegy, ntrc;
	int tmpns, tmpdt, tmpformat;
	FILE *fid=NULL;
	unsigned char segy_header[3600];
	unsigned char *buffer;

	if(argc==1)
	{
		usage();
		return(0);
	}

	//check ns, dt and format segy
	getBinaryHeaderInfo(argv[1], &ns, &dt, &format);
	for (i=2; i<argc; i++)
	{
		getBinaryHeaderInfo(argv[i], &tmpns, &tmpdt, &tmpformat);
		if(ns!=tmpns || dt!=tmpdt || format!=tmpformat)
		{
			fprintf(stderr,"segy_merge : ns, dt, or format segy not equal at index %i \n", i);
			return(1);
		}
	}

	if(format==1) nsegy = 240 + (ns*4);
	else if(format==2) nsegy = 240 + (ns*4);
	else if(format==3) nsegy = 240 + (ns*2);
	else if(format==4) nsegy = 240 + (ns*4);
	else if(format==5) nsegy = 240 + (ns*4);
	else if(format==8) nsegy = 240 + (ns);
	else
	{
		fprintf(stderr,"segy_merge : format file must be 1, 2, 3, 4, 5 or 8 \n");
		return(1);
	}

	// --------------- MERGE FILE --------------
	buffer = (unsigned char*) calloc(nsegy, sizeof(unsigned char));	//allocate header+trace
	for(i=1; i<argc; i++)
	{
		fid = fopen(argv[i], "r");
		if(!fid){
			fprintf(stderr,"Error opening file %s \n", argv[i]);
			exit(0);
		}
		ntrc = getNumberOfTraceSegyFile(fid, nsegy);	//get number of trace from segy file

		if(i==1)	//read and write segy header
		{
			result = fread(segy_header, sizeof(unsigned char), 3600, fid);
			result = fwrite(segy_header, sizeof(unsigned char), 3600, stdout);
		}
		else
			fseeko64(fid, 3600, SEEK_SET);	//skip reading segy header

		for(j=0; j<ntrc; j++)
		{
			if(j%1000==0)
				fprintf(stderr,"open file %i/%i, reading traces %i from %i \n",
						i, argc-1, j+1, ntrc);
			result = fread(buffer, sizeof(unsigned char), nsegy, fid);	//read trace
			result = fwrite(buffer, sizeof(unsigned char), nsegy, stdout);//write trace
		}
		fclose(fid);

	}

	free(buffer);
	fprintf(stderr,"Merging File Complete \n");
	return(1);
}

After compile this code, we can use this program with command :

segymerge input_segy1 input_segy2 …. input_segyn > output_segy_merge.sgy

or

segymerge *.sgy > output_segy_merge.sgy

This is the sample output log from this C/C++ SEGY merge program :

toto@toto-laptop$ segymerge file1.sgy file2.sgy file3.sgy >out.sgy
open file 1/3, reading traces 1 from 114972 
open file 1/3, reading traces 1001 from 114972 
open file 1/3, reading traces 2001 from 114972 
open file 1/3, reading traces 3001 from 114972

You can download the comple C/C++ SEGY merge code at here

Add a Comment

Your email address will not be published. Required fields are marked *