The following program will export an array of structures (including
structures that includes arrays and nested structures) to a csv file,
with a header that include the tag-names.
function mk_struct_data_format,struct1,iter
struct=struct1
tn=tag_names(struct)
ntn=n_elements(tn)
if n_elements(iter) eq 0 then iter = 0
format2=''
format3=strarr(ntn)
for i=0l,ntn-1 do begin
t=size(struct(0).(i),/type)
nel=''
nel_int=fix(size(struct(0).(i),/n_elements))
if nel_int ne 1 then nel=string(nel_int)
prefix=','
if i eq 0 and iter eq 0 then prefix=''
if t eq 7 then format3(i)=nel + '(A20,"|")'
if t eq 8 then format3(i)=mk_struct_data_format(struct(0).(i),0)
if t ne 7 and t ne 8 then format3(i)=nel + '(F20.8,"|")'
endfor
count=0
format4=''
prefix=''
for i=0l,ntn-1 do begin
if i eq 0 then begin
curr_format=format3(i)
count=1
endif
if i ne 0 then begin
if format3(i) eq curr_format then count=count+1
if format3(i) ne curr_format then begin
format4=format4+prefix+string(count)+'('+curr_format+')'
count = 1
curr_format=format3(i)
if prefix eq '' then prefix=','
endif
endif
;print,i,curr_format,count
endfor
format4=format4+prefix+string(count)+'('+curr_format+')'
format4=strcompress(format4,/remove_all)
return,format4
end
function get_all_tagnames,struct,prefix=prefix
FORWARD_FUNCTION get_all_tagnames
if n_elements(prefix) eq 0 then prefix=''
tn=tag_names(struct)
ntn=n_elements(tn)
if n_elements(iter) eq 0 then iter = 0
out=['']
for i=0l,ntn-1 do begin
t=size(struct(0).(i),/type)
nel=size(struct(0).(i),/n_elements)
if nel eq 1 then begin
if t ne 8 then out=[out,strcompress(prefix+tn(i),/remove_all)]
if t eq 8 then
out=[out,get_all_tagnames(struct(0).(i),prefix=strcompress(t n(i)+'_',/remove_all))]
endif
if (nel ne 1 and t ne 8) then
out=[out,strcompress(prefix+tn(i)+string(indgen(nel)),/remov e_all)]
endfor
out=out(1:*)
return,out
end
function remove_big_arr,in,maxarr
out=in
tmp=0
for i=0,n_tags(in)-1 do begin
if n_elements(in(0).(i)) gt maxarr then tmp=[tmp,i]
endfor
if n_elements(tmp) gt 1 then begin
out=delete_tags(in,tmp(1:*))
return,out
endif else return,in
end
pro write_struct_psv,in1,fname,maxarr=maxarr
in=in1
close,7
openw,7,fname
if keyword_set(maxarr) then in=remove_big_arr(in,maxarr)
tn=get_all_tagnames(in)
for i=0l,n_elements(tn)-1 do tn(i)=strcompress(tn(i),/remove_all)
ntn=n_elements(tn)
nin=n_elements(in)
format1=strcompress('('+ string(ntn) +'(A20,"|"))',/remove_all)
;print,format1
printf,7,format=format1,tn
format2=mk_struct_data_format(in)
format2=strcompress('('+format2+')',/remove_all)
for i=0l,nin-1 do begin
printf,7,format=format2,in(i)
endfor
close,7
end
|