c++怎么用fseek函数定位?

#include<iostream>
#include <fstream>
#include <string>
#include <string.h>
using namespace std;

void main()
{
//在文件中写入学号和科目
string number;
string name;
ofstream outstuf ; 
outstuf.open( "test.txt" , ios::app|ios::binary ) ; 
if ( !outstuf ) 
{ cerr << "文件不存在" << endl ; abort(); }
cin>>number;
number=number+" ";
outstuf.seekp(0,ios::end); //多这名,文件指针移到尾
outstuf<<number.c_str();

怎么用fseek()使得指针能指向到number后面,指向文件里面number的后面?

尚方宝剑之说
浏览 1102回答 3
3回答

qq_笑_17

int fseek(FILE *stream, long offset, int fromwhere);函数设置文件指针stream的位置。如果执行成功,stream将指向以fromwhere(偏移起始位置:文件头0(SEEK_SET),当前位置1(SEEK_CUR),文件尾2(SEEK_END))为基准,偏移offset(指针偏移量)个字节的位置。如果执行失败(比如offset超过文件自身大小),则不改变stream指向的位置。也就是写成 fseek(outstuf,0,2);

繁星点点滴滴

函数fseek使用指南1.函数原型:int fseek ( FILE * stream, long int offset, int origin );2. 函数功能:Sets the position indicator associated with the stream to a new position.For streams open in binary mode, the new position is defined by adding offset to a reference position specified by origin.For streams open in text mode, offset shall either be zero or a value returned by a previous call to ftell, and origin shall necessarily be SEEK_SET.If the function is called with other values for these arguments, supportdepends on the particular system and library implementation(non-portable).The end-of-file internal indicator of the stream is cleared after a successful call to this function, and all effects from previous calls to ungetc on this stream are dropped.On streams open for update (read+write), a call to fseek allows to switch between reading and writing.3. 函数参数streamPointer to a FILE object that identifies the stream.offsetBinary files: Number of bytes to offset from origin.Text files: Either zero, or a value returned by ftell.originPosition used as reference for the offset. It is specified by one of the following constants defined in <cstdio> exclusively to be used as arguments for this function:ConstantReference positionSEEK_SET Beginning of fileSEEK_CUR Current position of the file pointerSEEK_END End of file ** Library implementations are allowed to not meaningfully support SEEK_END (therefore, code using it has no real standard portability).4. 返回值If successful, the function returns zero.Otherwise, it returns non-zero value.If a read or write error occurs, the error indicator (ferror) is set.5. 例程#include <stdio.h>int main (){FILE * pFile;pFile = fopen ( "example.txt" , "wb" );fputs ( "This is an apple." , pFile );fseek ( pFile , 9 , SEEK_SET );fputs ( " sam" , pFile );fclose ( pFile );return 0;}After this code is successfully executed, the file example.txt contains:This is a sample
打开App,查看更多内容
随时随地看视频慕课网APP