文档库 最新最全的文档下载
当前位置:文档库 › High-speed 3-D shape measurement based on digital fringe projection

High-speed 3-D shape measurement based on digital fringe projection

High-speed 3-D shape measurement based on digital fringe projection
High-speed 3-D shape measurement based on digital fringe projection

High-speed3-D shape measurement based on digital fringe projection

Peisen S.Huang

Chengping Zhang

Fu-Pen Chiang

SUNY at Stony Brook

Department of Mechanical Engineering Stony Brook,New York11794-2300

E-mail:chenzhan@https://www.wendangku.net/doc/3b5576332.html, Abstract.A high-speed3-D shape measurement technique based on digital fringe projection has been developed and experimented.This technique uses a computer-generated color fringe pattern whose red, green,and blue channels are sinusoidal fringe patterns with a120-deg phase shift between neighboring channels.When this color fringe pat-tern is sent to a digital-micromirror-device(DMD)based video projector with no color?lter,three gray-scale fringe patterns are repeatedly pro-jected to an object surface in sequence with a cycle time of approxi-mately10ms.The three phase-shifted fringe patterns deformed by the object surface are captured by a CCD camera with proper synchroniza-tion between the camera and the projector.The3-D shape of the object surface is reconstructed by using a phase wrapping and unwrapping algorithm and a phase-coordinate conversion algorithm.Experimental results demonstrated the feasibility of this technique for high-speed3-D shape measurement with a potential measurement speed up to100Hz.?2003Society of Photo-Optical Instrumentation Engineers.[DOI:10.1117/1.1525272] Subject terms:fringe projection;phase shifting;digital micromirror device;3-D shape measurement.

Paper020014received Jan.17,2002;revised manuscript received May29, 2002;accepted for publication May29,2002.

1Introduction

Accurate3-D shape measurement plays an increasingly im-

portant role in the industry’s quest for higher productivity

and product quality.Currently,3-D surface coordinates are

often measured by coordinate measurement machines ?CMMs?.A CMM requires point-by-point scanning,which is time consuming and therefore cannot meet the require-

ment of on-line measurement.Moreover,its contacting na-

ture prohibits its application to the measurement of delicate

surfaces.Hence,interest has been growing in using optical

methods to measure3-D shapes of objects because of their

speed,accuracy,sensitivity,as well as their noncontact and

nondestructive characteristics.Various optical methods

have been developed for3-D shape measurement including

some high-speed optical techniques.1–11Harding proposed

a color-encoded moire′technique for high-speed surface

contouring.7Geng developed a rainbow3-D camera that

can capture the3-D information of an object surface at the

frame rate of the camera.8Huang et al.proposed a color-

encoded digital fringe projection technique,which allowed

for the3-D surface contour information to be retrieved

from a snapshot of the object surface.9However,since

color was used in all these techniques as the means to re-

trieve the3-D information of the object surface,measure-

ment errors could be introduced by the original color of the

object surface if it were not neutral.

We describe a novel high-speed phase shifting technique

for rapid3-D shape measurement.This technique uses a

digital-light-processing?DLP?video projector,which is

based on digital-micromirror-device?DMD?technology for

fringe projection.It takes advantage of the fact that a single-chip DLP projector projects the red,green,and blue ?RGB?color channels sequentially and in high speed to form24-bit color images.A color-encoded fringe pattern is created,which consists of three fringe patterns,one in each color channel,with a phase shift of2?/3between neigh-boring color channels.The color?lter of the projector is removed so that the projected fringe patterns are actually all in the gray-scale mode.By synchronizing the image capture of a camera with the fringe projection of the pro-jector,it is possible to capture the three phase-shifted fringe patterns in less than10ms,thus signi?cantly increasing the speed of3-D shape measurement.

Section2introduces the DLP and DMD technology and how it can be used in the proposed high-speed phase shift-ing technique for3-D shape measurement.Section3dis-cusses issues related to the synchronization of the camera and the projector.The experimental results are presented in Sec.4and conclusions given in Sec.5.

2Principle

DLP is an all-digital projection display technology devel-oped by Texas Instruments.Central to the DLP technology is an optical switch called DMD.12,13DMD consists of an array of tiny mirrors,each operating in a bistable mode, tilting diagonally?10deg?ON?or?10deg?OFF?about the hinge attached to the support post.The proportion of time during each video frame that a micromirror remains ON determines the shade of pixel gray scale from black for zero ON-time to white for100%ON-time.

Figure1shows the con?guration of a DLP projector with one DMD chip.The light from the illuminator is?rst focused to a small spot on the color?lter.The color?lter spins at high speed,producing red,green,and blue light

163

Opt.Eng.42(1)163–168(January2003)0091-3286/2003/$15.00?2003Society of Photo-Optical Instrumentation Engineers

sequentially that illuminates the DMD surface.The image to be projected is formed on the DMD chip.Since there is only one DMD chip in the projector,but a 24-bit color image is to be projected,the projector operates in a unique color-channel-switching mode.At one speci?c moment only one channel of the color image,red,green or blue,is projected and the three color channels are projected in se-quence.A photodiode mounted on the cover of the DMD projection engine monitors the position of the color ?lter by measuring the scattered light after the color ?lter.For each segment of the color ?lter,the photodiode provides a dif-ferent photocurrent to the projector.Based on this current,the DMD forms the image of the corresponding color chan-nel.Since the color channels are switched at high speed,what the viewer sees is a 24-bit color image.

In this research,a DLP projector is modi?ed and used to project fringe patterns for 3-D shape measurement.Because of the unique color-channel-switching characteristic of the DLP projector,not only highly precise phase shifting can be achieved,the phase shifting speed can also be increased signi?cantly.The traditional ways of phase shifting by physically moving a grating or a reference mirror are inher-ently slow and cannot avoid phase shifting errors intro-duced during the phase shifting process.The principle of this high-speed phase shifting technique is shown in Fig.2.A color-encoded fringe pattern is generated in a personal computer with individual color channels programmed to be sinusoidal fringe patterns with 2?/3apart in phase.That is:

I R ?255?1?cos ?2?x /p ?2?/3??/2,?1?I G ?255?1?cos ?2?x /p ??/2,?2?I B ?255?1?cos ?2?x /p ?2?/3??/2,

?3?

where I R ,I G ,and I B are the gray-scale values of the red,green,and blue channel,respectively,255is the maximum gray scale of the DLP projector that we use,x is the hori-zontal pixel index of DMD,and p is the fringe pitch in pixels.When this fringe pattern is sent to the DLP projec-tor,the three color channels are sequentially and repeatedly projected onto the object surface with a cycle time of 10ms.To eliminate the effect of color on the measurement results,the color ?lter is removed,which makes the pro-jected fringe patterns to be gray scale.By synchronizing image capture with fringe projection and correctly captur-ing these phase-shifted fringe patterns,we obtain:I 1?i ,j ??I ??i ,j ??I ??i ,j ?cos ???i ,j ??2?/3?,?4?I 2?i ,j ??I ??i ,j ??I ??i ,j ?cos ???i ,j ??,?5?I 3?i ,j ??I ??i ,j ??I ??i ,j ?cos ???i ,j ??2?/3?,

?6?

where i ,j are the CCD pixel indices,I 1(i ,j ),I 2(i ,j ),and I 3(i ,j )are the intensities of the three phase-shifted images,respectively,I ?(i ,j )is the average intensity and I ?(i ,j )is the intensity modulation,and ?(i ,j )is the phase map of the fringe pattern.By solving these three equations,?(i ,j )can be obtained as:

??i ,j ??arctan

?

?3

I 1?I 3

2I 2?I 1?I 3

?

.

?7?

By calculating the relative phase difference of the neigh-boring pixels and removing the 2?discontinuity,a continu-ous phase map representing the 3-D shape of the object surface is obtained.With calibration and a phase-coordinate conversion algorithm,the phase map can be further con-verted to (x ,y ,z )coordinate values.10

The time for capturing one fringe pattern based on this principle is 2.5ms.Because the color ?lter has a

clear

Fig.1Con?guration of a one-DMD

projector.

Fig.2Principle of the new high-speed phase shifting method.

164

Optical Engineering,Vol.42No.1,January 2003

segment as well as the three color segments,up to 300phase-shifted fringe patterns can be recorded in one second.Currently the data are processed of?ine,and a measurement result with a sampling rate up to 100Hz could be recon-structed.Should parallel image processing capability be available,i.e.,captured images are processed at the same time during the image acquisition,a potential real-time 3-D shape measurement speed of 100Hz could be obtained.The actual speed may be limited by the sampling speed of the camera and the frame grabber.Another advantage of this technique,as compared to other high-speed 3-D shape measurement techniques,lies in the fact that it uses gray-scale fringe patterns and therefore it does not have the po-tential problems associated with color.This will greatly broaden the scope of application for this technique.3

Synchronization of the Projector and Camera

In the DLP projector we used,the timing signal is gener-ated by a photosensor mounted on the cover of the DLP projection engine.This photosensor measures the scattered light after the color ?lter,which has four segments:red,green,blue,and clear.The clear segment is used to increase the overall brightness of the projected image.When the color ?lter spins,the photosensor picks up a pulsed signal with four levels of amplitude,each corresponding to one of the four colors.This signal is used in the projector to con-trol the timing of the DMD for the projection of the color channels,as shown in Fig.3.Through experiments,we found that only one falling edge in each projection cycle of the signal was actually used to trigger the DMD.Once triggered,the DMD projects three color channels sequen-tially with a ?xed time interval.Since the color ?lter is removed in this research to allow for the projection of gray-scale fringe patterns,this timing signal from the photosen-sor is no longer available.Therefore,an external timing signal is necessary to keep the projector working.We de-veloped a timing signal generation circuit with a microcon-troller Atmel 89c51,a derivative of the industrial standard Intel 80c51family.This microcontroller generates the tim-ing signal using a digital-to-analog ?D/A ?converter.Since the D/A converter gives a voltage signal while a photodiode generates a current signal,a voltage-to-current conversion

was included to guarantee the compatibility.The timing signal generated is a square wave signal with a frequency of approximately 100Hz.In addition to the timing signal for the DLP projector,the circuit also generates three trig-ger pulses for the camera,each corresponding to the red,green,and blue channels of the projector.These trigger pulses start after the timing pulse of the projector and in the sequence of red,green,and blue.The time delay between the neighboring channels is approximately 2.5ms.Accurate timing is important to the correct capture of the phase-shifted fringe patterns in sequence.

To test the feasibility of this approach to synchronize the projector and the camera,three monochromatic letters,in red,green,and blue,respectively,were projected onto a screen.By optimizing the time delay between the trigger signals for DMD projection and CCD acquisition,we were able to capture a single color channel in one picture.The fact that there are no coupling effects between the color channels shows that the high-speed phase shifting principle is viable and the synchronization method works well.4

Experiments

The gray-scale curve,which represents the relationship be-tween the input gray-scale value and the output intensity,in the commercial video projectors is purposely distorted for best visual effect.Moreover,on the removal of the color ?lter,the three color channels are no longer in balance.For measurement applications,a linear gray-scale curve is de-sired for better measurement accuracy.Thus,linearity com-pensation of the gray-scale curve becomes a necessary step.To obtain the gray-scale curves for each color channel,three red,green,and blue images with uniform intensity were projected sequentially onto a white ?at surface with uniform re?ectivity.A CCD camera is used to capture the re?ected images and the gray-scale values in an area of 10?10pixels in the center of the image are averaged and recorded.By changing the projected image intensity at a constant step from maximum to minimum,and repeating the measurements,the gray-scale curves before and after linearity compensation are measured.Figure 4shows the measured gray-scale curves for the red,green,and blue channels.These curves can be ?t using

polynomials:

Fig.3Timing signal from the photodiode inside the

projector.

Fig.4Gray-scale curves before linearity compensation.

165

Optical Engineering,Vol.42No.1,January 2003

f R?I in??r0?r1I in?r2I in2?ˉ?r i I in i,?8?f G?I in??g0?g1I in?g2I in2?ˉ?

g i I in i,?9?f B?I in??b0?b1I in?b2I in2?ˉ?b i I in i,?10?where I in is the input gray-scale value to the projector, f R(I in),f G(I in),and f B(I in)are the gray-scale curves for the red,green,and blue channels,respectively,and r i,g i, and b i are the coef?cients of three polynomial functions. For the input gray scales?40,the actual projected gray scale does not change muc

h for all the three channels,so the curves with I in?40are abandoned.We found that the

gray-scale curves could be suf?ciently and accurately de-scribed with up to seventh-order terms,so higher-order terms were eliminated to simplify the calculation.Ideally, consistent outputs from the three channels are desired,so the useable gray-scale range for the three channels is be-tween:

Upper Limit?min?f R?255?,f G?255?,f B?255??,?11?and

Lower Limit?max?f R?40?,f G?40?,f B?40??.?12?Any gray-scale value beyond this range will not be able to be projected by certain channels.The ideal linear output can be derived as:

I out?Lower Limit?Upper Limit?Lower Limit

255?40

??I in?40?,?13?then the three input gray-scale values after linearity com-pensation are:

I in-R?f R?1?I out?,?14?

I in-G?f G?1?I out?,?15?

I in-B?f B?1?I out?,?16?where I in-R,I in-G,and I in-B are the compensated input gray-scale values for the red,green,and blue channels, f R?1(),f G?1(),and f B?1()are the inverse functions of those de?ned by Eqs.?8?–?10?.The compensated gray-scale curves are shown in Fig.5.Apparently the linearity of the curves has been signi?cantly improved.

Some measurements were performed after the linearity compensation.With the current setup,the measurement speed is mainly limited by the frame rate of the CCD cam-era,which can go only up to85frames/sec,while the pro-jector can provide300phase shifting steps per second.In this experiment,one phase-shifted fringe pattern was cap-tured by the CCD camera every two projection cycles, which resulted in a frame rate of50frames/sec or163-D measurements per second.The?rst object measured was a plaster casting.Figures6?a?–8?f?show the2-D image of the object,the three phase-shifted fringe patterns,the wrapped phase,and the reconstructed3-D shape,respec-tively.A human face was also measured.When measuring a live human body,the measurement speed is critical because any slight body movement would introduce large errors. Figure7shows the measurement results and the recon-structed3-D shape.A simple geometrical relationship was used to convert the phase map to actual surface height.6A measurement resolution of1mm was achieved with a mea-surement area of25?18cm.Although the gray-scale curves for the three channels are compensated for,they were still not completely identical,which was the major source of the system error.This error can be further

sup-Fig.5Gray-scale curves after linearity

compensation.

Fig.6Measurement results of a plaster head.

166Optical Engineering,Vol.42No.1,January2003

pressed by using the phase averaging algorithm at the cost of the measurement speed.14It can be seen clearly that the reconstructed 3-D human face is fairly smooth,which dem-onstrates the advantage of this high-speed phase shifting technique in terms of measurement speed.

Finally,the maximum speed of this phase-shifting tech-nique was tested.The highest frame rate for the Kodak ES310camera is 85frames/sec for full frame.However,it provides a special operation mode called ‘‘block readout mode,’’which allows us to choose a portion of the image to be read out at a higher frame rate.The block size changes the effective frame rate;a smaller block takes less time to read out and therefore results in a higher frame rate.In this experiment,a block size of 40rows was selected,which enabled a frame rate close to 300frames/sec.Figure 8

shows a chessboard-like image that contains multiple blocks.Each block was taken at one phase step and three consecutive blocks were taken within one projection cycle of 10ms.This image demonstrates that the highest mea-surement speed of the technique can be as fast as 1003-D measurements per second,provided that the camera can keep up with the speed.

5Conclusions

A novel high-speed phase shifting technique for 3-D shape measurement with a potential measurement speed of 100Hz has been developed.It takes advantage of the unique color channel switching characteristic of a DLP projector with one DMD chip.By removing the color ?lter and prop-erly synchronizing the projection of fringe patterns by the DLP projector and the acquisition of images by the CCD camera,three phase-shifted fringe patterns can be obtained within 10ms.This makes it possible to achieve a maximum measurement speed of 100Hz or 1003-D shape measure-ments per second if the sampling speed of the CCD camera is fast enough.A compensation algorithm was developed to eliminate the effect of the gray-scale curve distortion of the digital projectors,and as a result,satisfactory results were obtained.Experimental results showed that this method could be used to measure the 3-D shapes of slowly moving objects,which has been dif?cult to accomplish by the tra-ditional phase shifting 3-D shape measurement systems.

Acknowledgments

This work was supported by the National Science Founda-tion under Grant No.DMI-9713895and CMS-9900337and the National Institute of Health under Grant No.RR13995.

References

1.L.H.Bieman,‘‘Survey of design considerations for 3-D imaging systems,’’Proc.SPIE 1005,138–144?1988?.

2.F.Blais and M.Rioux,‘‘BIRIS:a simple 3-D sensor,’’Proc.SPIE 723,235?1986?.

3.D.J.Svetkoff,P.F.Leonard,and R.E.Sampson,‘‘Techniques for real-time,3D,feature-extraction using range information,’’Proc.SPIE 521,302–309?1985?.

4.D.M.Meadows,W.O.Johnson,and J.B.Allen,‘‘Generation of

surface contours by Moire

′patterns,’’Appl.Opt.9,942–947?1970?.5.R.E.Brooks and L.O.He?inger,‘‘Moire

′gauging using optical in-terference patterns,’’Appl.Opt.16?8?,2152–2162?1977?.

6.V .H.Srinivasan,H.-C.Liu,and M.Halious,‘‘Automated phase-measuring pro?lometry for 3D diffuse objects,’’Appl.Opt.23?18?,3105–3108?1984?.

7.K.G.Harding,‘‘Color encoded moire

′contouring,’’Proc.SPIE 1005,169–178?1988?.

8.Z.J.Geng,‘‘Rainbow 3-D camera:new concept of high-speed three dimensional vision system,’’Opt.Eng.35?2?,376–383?1996?.

9.P.S.Huang,Q.Hu,F.Jin,and F.P.Chiang,‘‘Color-encoded digital fringe projection technique for high-speed three dimensional surface contouring,’’Opt.Eng.38?6?,1065–1071?1999?.

10.Q.Hu,P.S.Huang,Q.Fu,and F.P.Chiang,‘‘Calibration of a 3D

surface contouring and ranging system,’’Proc.SPIE 3835,158–166?1999?.

11.D.M.Freeman,A.J.Aranyosi,M.J.Gordon,and S.S.Hong,‘‘Mul-tidimensional motion analysis of MEMS using computer microvi-sion,’’Solid-State Sensor Actuator Workshop ,Hilton-Head Island,SC,June 8–11?1998?.

12.L.J.Hornbeck,‘‘Current status of the digital micromirror device

?DMD ?for projection television applications,’’Intl.Electron.Devices Tech.Digest ,pp.381–384?1993?.

13.J.M.Younse,‘‘Mirrors on a chip,’’IEEE Spectrum ,pp.27–31?Nov.

1993?.

14.P.Hariharan,‘‘Phase-shifting interferometry:minimization of system-atic errors,’’Opt.Eng.39?4?,967–969?2000?

.

Fig.7Measurement results of a human

face.

Fig.8Captured fringe patterns with a frame rate of 300frames/sec.

167

Optical Engineering,Vol.42No.1,January 2003

Peisen S.Huang received his BS degree

in precision instrumentation engineering in

1984from Shanghai Jiao Tong University,

People’s Republic of China and his ME de-

gree in precision engineering in1988from

Tohoku University,Japan.He then re-

ceived a PhD degree in mechanical engi-

neering in1993from The University of

Michigan,Ann Arbor and DrEng degree in

precision engineering and mechatronics in

1995from Tohoku University,Japan.He

joined the Department of Mechanical Engineering,SUNY at Stony

Brook as an assistant professor in1993and is now an associate

professor and the director of the Optical Metrology Laboratory.His

research interests include optical metrology,instrument design,3-D

machine vision,and image processing.He is currently a member of

SPIE.

Chengping Zhang received his BS and

MS in Mechanical Engineering from Zhe-

jiang Univeristy,China,in1995and1998,

respectively,and PhD in mechanical engi-

neering from SUNY at Stony Brook in

2001.His is currently a senior systems de-

sign engineer at Potomac Photonics,Inc.

His research interests include optical in-

strumentation,mechatronics,machine vi-

sion,laser micromachining and its applica-

tions in microelectronics,and semi-

conductor manufacturing.He is a member of SPIE and

IMAPS.

Fu-pen Chiang has been working in the

?eld of applied optics for many years with

contributions to the development of moire′

methods,photoelasticity,laser and white

speckle methods,holographic interferom-

etry,etc.with emphasis on applying these

techniques to problems such as fracture,

fatigue,and damage of materials and

structures.He is a fellow of the Optical So-

ciety of America,Society of Experimental

Mechanics.He was the editor of the Int.J.

of Optics and Lasers for8years and served as guest editor of Op-

tical Engineering for two special issues,associate editor of Experi-

mental Mechanics and ASME J.of Engineering Materials and Tech-

nology.

168Optical Engineering,Vol.42No.1,January2003

C语言程序中关于文件的操作

文件操作函数C语言(FILE fputc fgetc fputs fgets fscanf fprintf) 在ANSI C中,对文件的操作分为两种方式,即流式文件操作和I/O文件操作,下面就分别介绍之。 一、流式文件操作 这种方式的文件操作有一个重要的结构FILE,FILE在stdio.h中定义如下:typedef struct{ int level;/*fill/empty level of buffer*/ unsigned flags;/*File status flags*/ char fd;/*File descriptor*/ unsigned char hold;/*Ungetc char if no buffer*/ int bsize;/*Buffer size*/ unsigned char_FAR*buffer;/*Data transfer buffer*/ unsigned char_FAR*curp;/*Current active pointer*/ unsigned istemp;/*Temporary file indicator*/ short token;/*Used for validity checking*/ }FILE;/*This is the FILE object*/ FILE这个结构包含了文件操作的基本属性,对文件的操作都要通过这个结构的指针来进行,此种文件操作常用的函数见下表函数功能 fopen()打开流 fclose()关闭流 fputc()写一个字符到流中 fgetc()从流中读一个字符 fseek()在流中定位到指定的字符 fputs()写字符串到流 fgets()从流中读一行或指定个字符 fprintf()按格式输出到流 fscanf()从流中按格式读取 feof()到达文件尾时返回真值 ferror()发生错误时返回其值 rewind()复位文件定位器到文件开始处 remove()删除文件 fread()从流中读指定个数的字符 fwrite()向流中写指定个数的字符 tmpfile()生成一个临时文件流 tmpnam()生成一个唯一的文件名 下面就介绍一下这些函数 1.fopen() fopen的原型是:FILE*fopen(const char*filename,const char*mode),fopen实现三个功

Linux下C语言的文件读写

Linux下C语言的文件(fputc,fgetc,fwrite,fread对文件读写操 作) //================================== fputc 向文件写入字符 #include #include main() { FILE *fp; char ch; if((fp=fopen("test.txt","w"))==NULL) { printf("不能打开文件\n"); exit(0); } while ((ch=getchar())!='\n') fputc( ch, fp ); fclose(fp); } ------------- 小提示: fp=fopen("test.txt","w") ,把"w"改为"a" 可以创建文件并且追加写入内容 exit(0); 需要包含stdlib.h 头文件,才能使用 //============================================================ fgetc 读取字符 #include #include main( int argc, char *argv[] ) { char ch;

FILE *fp; int i; if((fp=fopen(argv[1],"r"))==NULL) { printf("不能打开文件\n"); exit(0); } while ((ch=fgetc(fp))!=EOF) putchar(ch); fclose(fp); } 文件结尾,通过判断EOF //============================================================== fwrite 的使用 使数组或结构体等类型可以进行一次性读写 #include #include main() { FILE *fp1; int i; struct student{ char name[10]; int age; float score[2]; char addr[15]; }stu; if((fp1=fopen("test.txt","wb"))==NULL) { printf("不能打开文件"); exit(0); } printf("请输入信息,姓名年龄分数1 分数2 地址:\n"); for( i=0;i<2;i++) { scanf("%s %d %f %f %s",https://www.wendangku.net/doc/3b5576332.html,,&stu.age,&stu.score[0],&stu.score[1], stu.addr);

c语言文件的读写格式

C程序文件的读写操作 在对文件进行读、写操作之前,首先要解决的问题是如何把程序中要读、写的文件与磁盘上实际的数据文件联系起来。在c语言中,其实这并不困难,只需要用c语言提供的库函数fopen“打开”文件就可以实现这些联系。Fopen函数的一般调用形式为: Fopen(文件名,文件使用方式); 函数返回一个指向file类型的指针。例如: FILE *fp; /*****定义一个文件指针*/ fp=fopen(”file_a”,”r”); foen函数调用中用两个字符串作为参数。第一个字符串中包含了进行读、写操作的文件名,用来指定所要打开的文件。在本例中,指定的函数名:file_a。第二个字符串中指定了文件的使用方式,用户可通过这个参数来指定对文件的使用意图。 如果以上函数调用成功,函数返回一个fille类型的指针,付给指针变量fp,从而把指针fp与文件file_a联系起来,也就是说,在此调用之后,指针fp就指向了文件file_a。 C语言中,最常用的文件使用用方式及其含义如下: (1)“r”。为读而打开文本文件。当指定这种形式时,对打开的文件只能进行“读”操作。若制定的文件不存在,则会出错,若去读一个不允许读的文件时也会出错。 (2)“rb”。为读而打开一个二进制文件,其余如“r”功能。 (3)“w”。为写而打开文本文件。这是。如果指定的文件不存在,系统将在指定位置建立一个新文件;如果文件已经存在,则将从文件的起始位置开始写,文件中原有内容将全部覆盖。 (4)“WB”. 为读而打开一个二进制文件,其余如“w”功能。 (5)“a”。为在文件后面添加数据而打开文本文件。这是。如果指定的文件不存在,系统将在指定位置建立一个新文件;如果文件已经存在,则将从文件的末尾位置开始写,文件中原有内容将保留。 (6)“ab”。为读而打开一个二进制文件,其余如“a”功能。 (7)“r+”。为读和写而打开文本文件。用这种方式时,指定的文件应当已经存在,既可以对文件进行读,也可以进行写。读写都是从文件起始位置开始。 关闭文件: fclose(文件指针); 程序例子: #include #include //fputc和fgetc函数所在文件 main() { FILE *fp=NULL; //定义文件指针 char ch; //定义字符变量 fp=fopen("d:\\wenjian.txt","w"); //打开或新建打开文件,并使指针 //指向文件 if(fp==NULL)

C语言读写文件操作

C语言读写文件操作 #include #include #include FILE *stream;//, *stream2; FILE *stream2; void main( void ) { int numclosed; char *list; list="这个程序由czw编写"; //试图打开文件data.txt,如果该文件不存在,则自动创建 if( (stream= fopen( "data.txt", "r" )) == NULL ) { printf( "试图打开'data.txt'\n" ); printf( "'data.txt'不存在\n" ); printf( "'data.txt'被创建\n" ); } else printf( "'data.txt'被打开\n" ); //以写入方式打开 if( (stream2 = fopen( "data.txt", "w+" )) == NULL ) printf( "'data.txt'不存在\n" ); else { printf( "'data.txt'成功被打开\n" ); fwrite(list,strlen(list),30,stream2); printf("写入数据成功\n"); } //如果文件data.txt存在,就会打开成功,则stream!=NULL,这时就关闭stream if (stream!=NULL) if( fclose( stream) ) printf( "文件流 stream 被关闭\n" ); //关闭所有打开的文件流,返回关闭的文件流个数 numclosed = _fcloseall( );

C语言中文件_数据的输入输出_读写

C语言中文件,数据的输入输出,读写. 文件是数据的集合体,对文件的处理过程就是对文件的读写过程,或输入输出过程。 所谓文件是指内存以外的媒体上以某种形式组织的一组相关数据的有序集合。文件分类: 顺序文件,随机文件。 文本文件和二进制文件。 文本文件也称为ASCII文件,在磁盘中存放时每个字符对应一个字节,用于存放对应的ASCII码。 文本文件可以在屏幕上按字符显示,源程序文件就是文本文件,由于是按字符显示,所以能读懂文件内容。 二进制文件是按二进制编码方式来存放的。这里主要讨论文件的打开,关闭,读,写,定位等操作。 文件的存取方法 C程序的输入输出(I/O)有两种方式:一种称为标准I/O或流式I/O,另一种称为低级I/O。流式I/O是依靠标准库函数中的输入输出函数实现的。低级I/O利用操作系统提供的接口函数(称为底层接口或系统调用)实现输入输出,低级I/O 主要提供系统软件使用。 在C语言中用一个FILE类型的指针变量指向一个文件,(FILE类型是系统在stdio.h中定义的描述已打开文件的一种结构类型),这个指针称为文件指针。FILE *指针变量标识符; 如 FILE *fp; 文件的打开与关闭 所谓打开文件,指的是建立文件的各种有关信息,并使文件指针指向该文件,以便对它进行操作。 关闭文件则是断开指针与文件之间的联系,也就禁止再对该文件进行操作。 1、fopen 函数原型:FILE *fopen(const char *filename,const char *mode); Fopen函数用来打开一个文件,前一部分用来说明文件路径及文件名,后一部分mode指出了打开文件的存取方式;返回值是被打开文件的FILE型指针,若打开失败,则返回NULL。打开文件的语法格式如下: 文件指针名=fopen(文件名,使用文件方式); 文件指针名必须被说明为FILE类型的指针变量。 FILE *fp; fp=fopen(“C:\\Windowss\\abc.txt”,”r”); 注意用两个反斜杠\\来表示目录间的间隔符。 存取文件的模式是一个字符串,可以由字母r,w,a,t,b及+组合而成,各字符的含

C语言文件读写函数集合

C语言文件读写函数 1.fopen() fopen的原型是:FILE *fopen(const char *filename,const char *mode),fopen 实现三个功能:为使用而打开一个流,把一个文件和此流相连接,给此流返回一个FILR指针。 参数filename指向要打开的文件名,mode表示打开状态的字符串,其取值如下: 字符串含义 "r" 以只读方式打开文件 "w" 以只写方式打开文件 "a" 以追加方式打开文件 "r+" 以读/写方式打开文件,如无文件出错 "w+" 以读/写方式打开文件,如无文件生成新文件 一个文件可以以文本模式或二进制模式打开,这两种的区别是:在文本模式中回车被当成一个字符’/n’,而二进制模式认为它是两个字符0x0D,0x0A;如果在文件中读到0x1B,文本模式会认为这是文件结束符,也就是二进制模型不会对文件进行处理,而文本方式会按一定的方式对数据作相应的转换。

系统默认的是以文本模式打开,可以修改全部变量_fmode的值来修改这个设置,例如_fmode=O_TEXT;就设置默认打开方式为文本模式;而 _fmode=O_BINARY;则设置默认打开方式是二进制模式。 我们也可以在模式字符串中指定打开的模式,如"rb"表示以二进制模式打开只读文件,"w+t"或"wt+"表示以文本模式打开读/写文件。 此函数返回一个FILE指针,所以申明一个FILE指针后不用初始化,而是用fopen()来返回一个指针并与一个特定的文件相连,如果成败,返回NULL. 例: 以下是引用片段: FILE *fp; if(fp=fopen("123.456","wb")) puts("打开文件成功"); else puts("打开文件成败"); 2.fclose() fclose()的功能就是关闭用fopen()打开的文件,其原型是:int fclose(FILE *fp);如果成功,返回0,失败返回EOF。 在程序结束时一定要记得关闭打开的文件,不然可能会造成数据丢失的情况,我以前就经常犯这样的错误。 例:fclose(fp); 3.fputc()

C语言文件操作命令

C语言文件操作函数大全 clearerr(清除文件流的错误旗标) 相关函数 feof 表头文件 #include 定义函数 void clearerr(FILE * stream); 函数说明 clearerr()清除参数stream指定的文件流所使用的错误旗标。 返回值 fclose(关闭文件) 相关函数 close,fflush,fopen,setbuf 表头文件 #include 定义函数 int fclose(FILE * stream); 函数说明 fclose()用来关闭先前fopen()打开的文件。此动作会让缓冲区内的数据写入文件中,并释放系统所提供的文件资源。 返回值若关文件动作成功则返回0,有错误发生时则返回EOF并把错误代码存到errno。 错误代码 EBADF表示参数stream非已打开的文件。 范例请参考fopen()。 fdopen(将文件描述词转为文件指针) 相关函数 fopen,open,fclose 表头文件 #include 定义函数 FILE * fdopen(int fildes,const char * mode); 函数说明 fdopen()会将参数fildes 的文件描述词,转换为对应的文件指针后返回。参数mode 字符串则代表着文件指针的流形态,此形态必须和原先文件描述词读写模式相同。关于mode 字符串格式请参考fopen()。 返回值转换成功时返回指向该流的文件指针。失败则返回NULL,并把错误代码存在errno中。 范例 #include main() { FILE * fp =fdopen(0,”w+”); fprintf(fp,”%s\n”,”hello!”); fclose(fp); } 执行 hello! feof(检查文件流是否读到了文件尾) 相关函数 fopen,fgetc,fgets,fread 表头文件 #include 定义函数 int feof(FILE * stream); 函数说明 feof()用来侦测是否读取到了文件尾,尾数stream为fopen()所返

C语言文件操作之绝对路径

C语言中对文件进行操作如何使用绝对路径? 我编了一个小程序试了一下,好像默认的路径是在生成的.exe文件所在目录下。如果使用像D:\\ABC.TXT这样的路径可以在D盘下对ABC.TXT进行操作,但如果使用D:\\SSS\ABC.TXT就不正确了,创建的文件是SSSABC.TXT,不支持多级的路径,它把路径和文件名弄混了。 到底怎么办 D:\\SSS\\ABC.TXT //你少了个\,在C字符串中,出现\的地方,你一律打两个\\就行了。 请问啊,C语言里,fopen、fread与fwrite的参数中,要求文件名,用写盘符吗? 写绝对路径吗?#include #include int main() { FILE *pfile = fopen("d:\\Jimmy.txt","wb");//Jimmy.txt写在D盘根目录下绝对路径//以2进制写入方式打开 //FILE *pfile = fopen("\\Jimmy.txt","wb");//Jimmy.txt写在当前目录下相对路径//以2进制写入方式打开 char sz[6] = "Billy"; fwrite("Jimmy",6,1,pfile);//将字串"Jimmy"写入文件pfile fclose(pfile); pfile = fopen("d:\\Jimmy.txt","rb");//以2进制读取方式打开绝对路径,D盘根目录 //pfile = fopen("\\Jimmy.txt","rb");//以2进制读取方式打开相对路径,当前路径 printf(sz);//显示原字串 printf("\n"); fread((char*)sz,6,1,pfile);//由开头读入6字节信息 printf(sz);//显示读取的信息 printf("\n"); fclose(pfile); system("pause"); return 0; }

C语言文件读写

C语言文件读写(基于缓冲技术) Syd168 2011.10.1 当文件按指定的工作方式打开以后,就可以执行对文件的读和写。下面按文件的性质分类进行操作。针对文本文件和二进制文件的不同性质,对文本文件来说,可按字符读写或按字符串读写;对二进制文件来说,可进行成块的读写或格式化的读写。 0. 文件打开与关闭 1. 读写字符 C提供fgetc和fputc函数对文本文件进行字符的读写,其函数的原型存于stdio.h头文件中,格式为: ?int fgetc(FILE *stream) fgetc( )函数从输入流的当前位置返回一个字符,并将文件指针指示器移到下一个字符处,如果已到文件尾,函数返回EOF,此时表示本次操作结束,若读写文件完成,则应关闭文件。 ?int fputc(int ch,FILE *stream) fputc()函数完成将字符c h的值写入所指定的流文件的当前位置处,并将文件指针后移一位。 fputc()函数的返回值是所写入字符的值,出错时返回EOF。 [例] 将存放于磁盘的指定文本文件按读写字符方式逐个地从文件读出,然后再将其显示到屏幕上。 采用带参数的main( ),指定的磁盘文件名由命令行方式通过键盘给定。

参数argc是用于记录输入参数的个数,argv是指针数组,用于存放输入参数的字符串,串的个数由argc描述。假设我们指定读取的文件名为L8-2.c,并且列表文件内容就是源程序。经过编译和连接生成可执行的文件L8-2.exe。运行程序l8-2.exe,输入的命令行方式为: c:\tc>l8-2 L8-2.c 上述程序以命令行方式运行,其输入参数字符串有两个,即argv[0]="c:\tc>l8-2"、argv[1]=" L8-2.c ",argc = 2。故打开的文件是L8-2.c 。程序中对fgetc( )函数的返回值不断进行测试,若读到文件尾部或读文件出错,都将返回C的整型常量EOF,其值为非零有效整数。程序的运行输出为源程序本身:c:\tc>l8-2 L8-2.c

C语言文件选择题

C语言文件选择题(答案在最后) 1、标准库函数fgets(s,n,f)的功能是 A) 从文件f中读取长度为n的字符串存入指针s所指的内存 B) 从文件f中读取长度不超过n-1的字符串存入指针s所指的内存 C) 从文件f中读取n个字符串存入指针s所指的内存 D) 从文件f中读取长度为n-1的字符串存入指针s所指的内存 2、在C中,对文件的存取以________为单位 A) 记录B) 字节 C) 元素D) 簇 3、下面的变量表示文件指针变量的是 A) FILE *fp B) FILE fp C) FILER *fp D) file *fp 4、在C中,下面对文件的叙述正确的是 A) 用“r”方式打开的文件只能向文件写数据 B) 用“R”方式也可以打开文件 C) 用“w”方式打开的文件只能用于向文件写数据,且该文件可以不存在 D) 用“a”方式可以打开不存在的文件 5、在C中,当文件指针变fp已指向“文件结束”,则函数feof(fp)的值是 A) .t. B) .F. C) 0 D) 1 6、在C中,系统自动定义了3个文件指针stdin,stdout和stderr分别指向终端输入、终端输出和标准出错输出,则函数fputc(ch,stdout)的功能是 A) 从键盘输入一个字符给字符变量ch B) 在屏幕上输出字符变量ch的值 C) 将字符变量的值写入文件stdout中 D) 将字符变量ch的值赋给stdout 7、下面程序段的功能是 #include main() {char s1; s1=putc(getc(stdin),stdout);} A) 从键盘输入一个字符给字符变量s1 B) 从键盘输入一个字符,然后再输出到屏幕 C) 从键盘输入一个字符,然后在输出到屏幕的同时赋给变量s1 D) 在屏幕上输出stdout的值 8、在C中,常用如下方法打开一个文件 if((fp=fopen("file1.c","r" ))==NULL) {printf("cannot open this file \n");exit(0);} 其中函数exit(0)的作用是

C语言中文件,数据的输入输出,读写

文件 文件是数据的集合体,对文件的处理过程就是对文件的读写过程,或输入输出过程。 所谓文件是指内存以外的媒体上以某种形式组织的一组相关数据的有序集合。文件分类: 顺序文件,随机文件。 文本文件和二进制文件。 文本文件也称为ASCII文件,在磁盘中存放时每个字符对应一个字节,用于存放对应的ASCII码。 文本文件可以在屏幕上按字符显示,源程序文件就是文本文件,由于是按字符显示,所以能读懂文件内容。 二进制文件是按二进制编码方式来存放的。这里主要讨论文件的打开,关闭,读,写,定位等操作。 文件的存取方法 C程序的输入输出(I/O)有两种方式:一种称为标准I/O或流式I/O,另一种称为低级I/O。流式I/O是依靠标准库函数中的输入输出函数实现的。低级I/O利用操作系统提供的接口函数(称为底层接口或系统调用)实现输入输出,低级I/O 主要提供系统软件使用。 在C语言中用一个FILE类型的指针变量指向一个文件,(FILE类型是系统在stdio.h中定义的描述已打开文件的一种结构类型),这个指针称为文件指针。FILE *指针变量标识符; 如 FILE *fp; 文件的打开与关闭 所谓打开文件,指的是建立文件的各种有关信息,并使文件指针指向该文件,以便对它进行操作。 关闭文件则是断开指针与文件之间的联系,也就禁止再对该文件进行操作。 1、fopen 函数原型:FILE *fopen(const char *filename,const char *mode); Fopen函数用来打开一个文件,前一部分用来说明文件路径及文件名,后一部分mode指出了打开文件的存取方式;返回值是被打开文件的FILE型指针,若打开失败,则返回NULL。打开文件的语法格式如下: 文件指针名=fopen(文件名,使用文件方式); 文件指针名必须被说明为FILE类型的指针变量。

C语言读写文件的例子

/*C语言使用文件打开文本文件读写的例子*/ 例1:功能:以文本方式生成一个文件,将"50 100 150"等数字输出到 文件中 #include void write_TXT_file(void) { const char * pFileName="c:\\aa.txt"; /*定义想输出的文件名及路径*/ int num1=50,num2=100,num3=150; /*定义输出到文件的数据*/ FILE * pFile; /*定义文件指针*/ pFile=fopen(pFileName,"wt"); /*以文本方式打开文件用于输出*/ if ( NULL == pFile ) /*判断打开文件成功否*/ { perror("打开文件失败"); return; } fprintf(pFile,"%d\n%d %d",num1,num2,num3); /*以文本方式输出到文件*/ if ( ferror(pFile) ) /*检验写文件是否成功*/ { perror("写文件失败"); fclose(pFile); /*关闭文件后返回*/ return; }; printf("文本文件成功写入\n"); fclose(pFile); /*不要忘记关闭文件*/ return; } 例2:/*功能:从文本文件中将数据读出来*/ void read_TXT_file(void) { const char * pFileName="c:\\aa.txt"; /*定义想读取的文件名*/ int num1,num2,num3; /*定义变量接收数据*/ FILE * pFile; /*定义文件指针*/ pFile=fopen(pFileName,"rt"); /*以文本方式打开文件用于输入*/ if ( NULL == pFile ) /*判断打开文件成功否*/ { perror("打开文件失败"); return; } fscanf(pFile,"%d%d%d",&num1,&num2,&num3); /*以文本方式读取文件*/

C语言文件读写

C语言文件读写 -- C语言的文件操作 文件的基本概念 所谓“文件”是指一组相关数据的有序集合。这个数据集有一个名称,叫做文件名。实际上在前面的各章中我们已经多次使用了文件,例如源程序文件、目标文件、可执行文件、库文件(头文件)等。文件通常是驻留在外部介质(如磁盘等)上的,在使用时才调入内存中来。从不同的角度可对文件作不同的分类。从用户的角度看,文件可分为普通文件和设备文件两种。 普通文件是指驻留在磁盘或其它外部介质上的一个有序数据集,可以是源文件、目标文件、可执行程序;也可以是一组待输入处理的原始数据,或者是一组输出的结果。对于源文件、目标文件、可执行程序可以称作程序文件,对输入输出数据可称作数据文件。 设备文件是指与主机相联的各种外部设备,如显示器、打印机、键盘等。在操作系统中,把外部设备也看作是一个文件来进行管理,把它们的输入、输出等同于对磁盘文件的读和写。通常把显示器定义为标准输出文件,一般情况下在屏幕上显示有关信息就是向标准输出文件输出。如前面经常使用的pri ntf,putchar 函数就是这类输出。键盘通常被指定标准的输入文件,从键盘上输入就意味着从标准输入文件上输入数据。scanf,getchar函数就属于这类输入。 从文件编码的方式来看,文件可分为ASCII码文件和二进制码文件两种。 ASCII文件也称为文本文件,这种文件在磁盘中存放时每个字符对应一个字节,用于存放对应的ASCII码。例如,数5678的存储形式为: ASC码:00110101 00110110 00110111 00111000 ↓ ↓↓ ↓ 十进制码:5678 共占用4个字节。ASCII码文件可在屏幕上按字符显示,例如源程序文件就是ASCII文件,用DOS命令TY PE可显示文件的内容。由于是按字符显示,因此能读懂文件内容。 二进制文件是按二进制的编码方式来存放文件的。例如,数5678的存储形式为:00010110 00101110只占二个字节。二进制文件虽然也可在屏幕上显示,但其内容无法读懂。C系统在处理这些文件时,并不区分类型,都看成是字符流,按字节进行处理。输入输出字符流的开始和结束只由程序控制而不受物理符号(如回车符)的控制。因此也把这种文件称作“流式文件”。 本章讨论流式文件的打开、关闭、读、写、定位等各种操作。文件指针在C语言中用一个指针变量指向一个文件,这个指针称为文件指针。通过文件指针就可对它所指的文件进行各种操作。定义说明文件指针的一般形式为:FILE* 指针变量标识符;其中FILE应为大写,它实际上是由系统定义的一个结构,该结构中含有文件名、文件状态和文件当前位置等信息。在编写源程

c语言读取csv文件

include #include #define MAX_LINE 128 typedef struct { char week[4]; char month[4]; char date[3]; char hour_minute_second[9]; char year[5]; } system_time_t;void main() { FILE*fp; float value; system_time_t system_time; char line[MAX_LINE]; if((fp=fopen("d:\\1.csv","r"))==NULL) { printf("Can't open d:\\1.csv\n"); } memset(&system_time,0,sizeof(system_time_t)); while(fgets(line, MAX_LINE, fp)) { sscanf(line,"%f , %s%s%s%s%s",&value, system_time.week, system_time.month, system_time.date, system_time.hour_minute_second, system_time.year); printf("value=%f system_time=%s %s %s %s %s\n", value, system_time.week, system_time.month, system_time.date, system_time.hour_minute_second, system_time.year); } } struct record_t { double money; time_t tim; };

C语言文件操作函数大全(超详细)讲解

C语言文件操作函数大全(超详细) 作者: 本篇文章是对C语言中的文件操作函数进行了详细的总结分析,需要的朋友参考下 fopen(打开文件)相关函数open,fclose 表头文件#include 定义函数FILE * fopen(const char * path,const char * mode); 函数说明参数path字符串包含欲打开的文件路径及文件名,参数mode字符串则代表着流形态。 mode有下列几种形态字符串:r 打开只读文件,该文件必须存在。 r+ 打开可读写的文件,该文件必须存在。 w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。 w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。 a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。 a+ 以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 r Open text file for reading. The stream is positioned at the beginning of the file. r+ Open for reading and writing. The stream is positioned at the beginning of the file. w Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file. w+ Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is posi‐ tioned at the beginning of the file. a Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the

C语言文件读写函数

C语言程序可以同时处理多个文件,为了对每一个文件进行有效的管理,在打开一个文件时,系统会自动地在内存中开辟一个区,用来存放文件的有关信息(如文件名、文件状态等) 这些信息保存在一个结构体变量中,该结构体是由系统定义的,取名为FILE。FILE定义在头文件stdio.h中。 对每一个要进行操作的文件,都需要定义一个指向FILE类型结构体的指针变量,该指针称为文件类型指针,文件类型指针的定义方法如下: FILE *指针变量; 如:FILE *fp; fp是一个指向FILE类型结构体的指针变量。当fp和某个文件建立关联之后,通过fp 即可找到存放该文件信息的结构变量,然后按结构变量提供的信息找到该文件,实施对文件的操作。 文件打开函数fopen() ?Fopen 函数的作用: 以指定方式打开指定文件。 打开成功,返回一个文件类型指针; 打开失败,则返回一个空指针NULL。 格式: FILE *文件指针变量; 文件指针变量=fopen(“文件名”, “文件使用方式”); “文件名”指要打开文件的名称。 “文件使用方式”指文件的类型和操作要求。如下表所示:

通常打开文件的方法: ? FILE *文件指针变量; 文件指针变量=fopen(“文件名”, “文件使用方式”); If(文件指针变量= =NULL) { printf(“cannot open this file\n”); exit(0); } 注:当打开文件出错时,函数 fopen 会返回一个空指针NULL 出错原因可能是以“r”方式打开一个不存在的文件,或者是磁盘已满等。关闭文件的函数: fclose(文件指针变量); 功能:用来关闭文件指针变量所指向的文件。成功返回0,否则返回非零值。 如:fclose(fp); 注:1 使用完一个文件后应即时关闭。否则会浪费系统资源。 2 关闭文件后,文件指针变量不再指向该文件,不能再通过该指针对该文件继续进行读写操作,除非再次打开该文件,使该指针变量重新指向该文件。

C语言实现读写二进制文件

C语言实现myql中存取二进制文件 include #include #include #include #include #include #define host "localhost" //mysql server #define username "root" #define password "cipher" #define database "www" int get_file_size(char *path, off_t *size) { struct stat file_stats; if(stat(path, &file_stats)) return -1; *size = file_stats.st_size; return 0; } int main(int argc, char *argv[]) { char *filename; off_t *size; MYSQL *conn; MYSQL_RES *res_set; MYSQL_ROW row; MYSQL_FIELD *field; int i, flag; char *sql; FILE *fp; char *buf; int n=0; char *end; unsigned long *length; if (argc != 2) { printf("Usage: %s srcfile\n", argv[0]); exit(1); } filename = argv[1]; if ((get_file_size(filename, size)) == -1) {

c语言文件读写方法

#include #define SIZE 5 struct student_type { int num; char name[10]; char sex[3]; int age; char addr[30]; char department[20]; char major[20]; char classes[20]; char state[20]; }stud[SIZE]; //txt文件读取 void read() { FILE *fp; int i; if((fp=fopen("stu.txt","r"))==NULL) //文件的放的位置是 .c文件夹下 { printf("cannot open file\n"); return; } for(i=0;i

c语言程序中文件的操作

c语言程序中文件的操 作 文件排版存档编号:[UYTR-OUPT28-KBNTL98-UYNN208]

文件操作函数 C语言 (FILE fputc fgetc fputs fgets fscanf fprintf) 在ANSI C中,对文件的操作分为两种方式,即流式文件操作和I/O文件操作,下面就分别介绍之。 一、流式文件操作 这种方式的文件操作有一个重要的结构FILE,FILE在中定义如下: typedef struct { int level; /* fill/empty level of buffer */ unsigned flags; /* File status flags */ char fd; /* File descriptor */ unsigned char hold; /* Ungetc char if no buffer */ int bsize; /* Buffer size */ unsigned char _FAR *buffer; /* Data transfer buffer */ unsigned char _FAR *curp; /* Current active pointer */ unsigned istemp; /* Temporary file indicator */ short token; /* Used for validity checking */ } FILE; /* This is the FILE object */ FILE这个结构包含了文件操作的基本属性,对文件的操作都要通过这个结构的指针来进行,此种文件操作常用的函数见下表函数功能 fopen() 打开流 fclose() 关闭流 fputc() 写一个字符到流中

C语言用指针和链表读写文件

#include #include #include #include #define MAXLEN_OF_KEYWORD 50 #define MAXLEN_OF_KEYWORDTYPE 30 char i,ch[5]; struct KeyWordBox { char Name[MAXLEN_OF_KEYWORD]; int Id; char Type[MAXLEN_OF_KEYWORDTYPE]; //该单词的类型struct KeyWordBox *next; //指针 }; void write(); void read(); void main() { write(); read(); } void write() { char *FileName="FileName.txt"; KeyWordBox transport; memset(&transport,0,sizeof(struct KeyWordBox)); FILE *out=NULL; FILE *test=NULL; test=fopen(FileName,"a"); if(test==NULL) { out=fopen(FileName,"w"); printf(" 1 continue,0 exit\n"); i=getchar(); while(i=='1') { printf("请输入关键字\n"); scanf("%s",https://www.wendangku.net/doc/3b5576332.html,); printf("请输入ID\n"); scanf("%d",&transport.Id); printf("请输入Type\n"); scanf("%s",transport.Type); fwrite(&transport,sizeof(struct KeyWordBox),1,out);

相关文档