c语言读取字符串?
有1个文件内有字符串数据,要求用C语言读取,有没有自带的函数啊
字符串数据有2种格式
1 定长字符串
2 不定长字符串
大家提点下,我就找到个fread函数,好象是说读取定长的,具体怎么用,也不清楚,问问
[解决办法]
fread
开放分类: 计算机语言、计算机技术、编程、程序、函数
函数名: fread
功 能: 从一个流中读数据
用 法: int fread(void *ptr, int size, int nitems, FILE *stream);
参 数:用于接收数据的地址(字符型指针)(ptr)
单个元素的大小(size)
元素个数(nitems)
提供数据的文件指针(stream)
返回值:成功读取的元素个数
程序例:
#include <string.h>
#include <stdio.h>
int main(void)
{
FILE *stream;
char msg[] = "this is a test";
char buf[20];
if ((stream = fopen("DUMMY.FIL", "w+"))
== NULL)
{
fprintf(stderr,
"Cannot open output file.\n");
return 1;
}
/* write some data to the file */
fwrite(msg, strlen(msg)+1, 1, stream);
/* seek to the beginning of the file */
fseek(stream, SEEK_SET, 0);
/* read the data and display it */
fread(buf, 1, strlen(msg)+1, stream);
printf("%s\n", buf);
fclose(stream);
return 0;
}
[解决办法]
size_t fread( void *buffer, size_t size, size_t count, FILE *stream );
The fread function reads up to count items of size bytes from the input stream and stores them in buffer. The file pointer associated with stream (if there is one) is increased by the number of bytes actually read. If the given stream is opened in text mode, carriage return–linefeed pairs are replaced with single linefeed characters. The replacement has no effect on the file pointer or the return value. The file-pointer position is indeterminate if an error occurs.
fread函数从输入流中读取最多count个大小为size个字节的项。文件指针关联的流增大实际读到的字节数。如果这个流是以文本模式打开的,回车新行对被单独的回车代替,这个行为不影响文件指针或返回值。如果发生错误,文件指针的位置不可预知。
#include <stdio.h>
void main( void )
{
FILE *stream;
char list[30];
int i, numread, numwritten;
/* Open file in text mode: */
if( (stream = fopen( "fread.out", "w+t" )) != NULL )
{
for ( i = 0; i < 25; i++ )
list[i] = (char)('z' - i);
/* Write 25 characters to stream */
numwritten = fwrite( list, sizeof( char ), 25, stream );
printf( "Wrote %d items\n", numwritten );
fclose( stream );
}
else
printf( "Problem opening the file\n" );
if( (stream = fopen( "fread.out", "r+t" )) != NULL )
{
/* Attempt to read in 25 characters */
numread = fread( list, sizeof( char ), 25, stream );
printf( "Number of items read = %d\n", numread );
printf( "Contents of buffer = %.25s\n", list );
fclose( stream );
}
else
printf( "File could not be opened\n" );
}