关于C语言读文件的问题,请教高人!

作者&投稿:冯潘 (若有异议请与网页底部的电邮联系)
关于C语言读CSV文件的问题~

csv文件即逗号分隔值文件。
逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。
纯文本意味着该文件是一个字符序列,不含必须像二进制数字那样被解读的数据。
CSV文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号或制表符。通常,所有记录都有完全相同的字段序列。
要用C语言读取CSV,首先需要确定文件中定义的字符分隔值,以及每一行各个列的元素格式。
如果所有的元素格式相同,那么可以每行一个一维数组,所有行组成一个二维数组,逐个元素进行读取。
如果元素格式不同,可以按照元素类型,构建一个结构体,每行读到一个结构体变量中,所有行组成一个结构体数组。
下面根据两种情况,按照分隔符为逗号(,),分别举一个例子:
文件名设定为in.csv,每行10个元素。
一、所有元素均相同类型,比如int型。
#include int main(){ FILE*fp; int a[100][10];//定义一个足够大的数组来存储。 int line = 0; int c, i; fp = fopen("in.csv", "r"); // 以文本方式打开。 if(fp == NULL) return -1; // 打开文件失败。 while(1) { i=0;//列标记清零。 while(1) { fscanf(fp, "%d", &a[line][i]);//从文件中读取一个元素。 c = getchar();//读取下一个字符,可能是分隔符,换行符或文件结尾。 if(c == '
'||c == EOF)break;//读完一行,或者到文件结尾,退出读取。 i++; } line ++; if(c == EOF) break; } fclose(fp); //关闭文件。 //以下循环用来打印所有读到的值。 for(i = 0; i < line; i ++) { for(c = 0; c < 10; c ++) printf("%d ", a[i][c]); printf("
"); } }二、每行元素不同。
比如共三列,第一列是int型,第二列是字符串,第三列是float型。
如果分隔符不是空白字符,或者字符串元素中可能存在除分隔符外的其它空白字符,在读取字符串的时候是不能用fscanf函数的。
定义结构体如下
strcut data{ int a; char s[100]; //根据实际要求,定义足够大的字符数组。 float f;};读取代码如下:
#include int main(){ FILE*fp; strcut data a[100];//定义一个足够大的结构体一维数组来存储。 int line = 0; int c,i; fp = fopen("in.csv", "r"); // 以文本方式打开。 if(fp == NULL) return -1; // 打开文件失败。 while(1) { fscanf(fp, "%d", &a[line].a);//从文件中读取第一个元素。 c = getchar();//读取分隔符。 //接下来要读取字符串,需要逐个字符读入,直到出现分隔符为止。 i = 0; while(1) { a[line].s[i] = getchar();//读入一个字符。 if(a[line].s[i] == ',')//发现分隔符 { a[line].s[i]='\0'; //赋值字符串结束符。 break;//退出读取字符串。 } i++; } //由于在读字符串的时候分隔符已经被读取,这里不需要读分隔符,而是直接读下一个元素。 fscanf(fp, "%f", &a[line].f);//从文件中读取最后一个元素。 c = getchar();//读取下一个字符,可能是换行符或文件结尾。 line ++; if(c == EOF) break;//到文件结尾,退出读取。 } fclose(fp); //关闭文件。 //以下循环用来打印所有读到的值。 for(i = 0; i < line; i ++) { printf("%d %s %f
", a[i].a, a[i].s, a[i].f); } }

产生随机数a,范围是0=<a<=x-1;
格式如下:
srand ( (unsigned) time (NULL) );
a=rand()%x; //a,x,均为整型变量,其中,x在之前应被赋值

对输入做了一些更改

#include
#include
#include

#define MaxSize 50
main ()
{
int m,n,d,i,count;
int A[MaxSize];
srand((unsigned int)time((time_t *)NULL));
n=rand()%MaxSize+1;
m=rand()%n+1;
printf("共有%d人,每次计数到%d出队
",n,m);
for(i=0;i<n;i++)
A[i]=i+1;
printf("*****************************
出队前:
");
for (i=0;i<n;i++)
{
printf("%d ",A[i]);
if((i+1)%5==0)
putchar('
');
}
printf("
*****************************
");
printf("出队后:
");
count=0;
d=0;
while(d<n)
for(i=0;i<n;i++)
if(A[i]!=0)
{
count++;
if (count==m)
{
printf("%d ",A[i]);
if((d+1)%5==0)
putchar('
');
A[i]=0;
count=0;
d++;
}
}
printf("
*****************************
");
}

fscanf比较方便!

NAME
scanf, fscanf, sscanf, vscanf, vsscanf, vfscanf - input format conversion
SYNOPSIS

#include <stdio.h>

int scanf(const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);
int sscanf(const char *str, const char *format, ...);

#include <stdarg.h>

int vscanf(const char *format, va_list ap);
int vsscanf(const char *str, const char *format, va_list ap);
int vfscanf(FILE *stream, const char *format, va_list ap);

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

vscanf(), vsscanf(), vfscanf(): _XOPEN_SOURCE >= 600 || _ISOC99_SOURCE; or cc -std=c99
DESCRIPTION
The scanf() family of functions scans input according to format as described below. This format may contain conversion specifications; the results from such conversions, if any, are stored in the locations pointed to by the pointer arguments that follow format. Each pointer argument must be of a type that is appropriate for the value returned by the corresponding conversion specification.

If the number of conversion specifications in format exceeds the number of pointer arguments, the results are undefined. If the number of pointer arguments exceeds the number of conversion specifications, then the excess pointer arguments are evaluated, but are otherwise ignored.

The scanf() function reads input from the standard input stream stdin, fscanf() reads input from the stream pointer stream, and sscanf() reads its input from the character string pointed to by str.

The vfscanf() function is analogous to vfprintf(3) and reads input from the stream pointer stream using a variable argument list of pointers (see stdarg(3). The vscanf() function scans a variable argument list from the standard input and the vsscanf() function scans it from a string; these are analogous to the vprintf(3) and vsprintf(3) functions respectively.

The format string consists of a sequence of directives which describe how to process the sequence of input characters. If processing of a directive fails, no further input is read, and scanf() returns. A "failure" can be either of the following: input failure, meaning that input characters were unavailable, or matching failure, meaning that the input was inappropriate (see below).

A directive is one of the following:


A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.

An ordinary character (i.e., one other than white space or '%'). This character must exactly match the next character of input.

A conversion specification, which commences with a '%' (percent) character. A sequence of characters from the input is converted according to this specification, and the result is placed in the corresponding pointer argument. If the next item of input does not match the conversion specification, the conversion fails --- this is a matching failure.

Each conversion specification in format begins with either the character '%' or the character sequence "%n$" (see below for the distinction) followed by:


An optional '*' assignment-suppression character: scanf() reads input as directed by the conversion specification, but discards the input. No corresponding pointer argument is required, and this specification is not included in the count of successful assignments returned by scanf().

An optional 'a' character. This is used with string conversions, and relieves the caller of the need to allocate a corresponding buffer to hold the input: instead, scanf() allocates a buffer of sufficient size, and assigns the address of this buffer to the corresponding pointer argument, which should be a pointer to a char * variable (this variable does not need to be initialized before the call). The caller should subsequently free(3) this buffer when it is no longer required. This is a GNU extension; C99 employs the 'a' character as a conversion specifier (and it can also be used as such in the GNU implementation).

An optional decimal integer which specifies the maximum field width. Reading of characters stops either when this maximum is reached or when a non-matching character is found, whichever happens first. Most conversions discard initial whitespace characters (the exceptions are noted below), and these discarded characters don't count towards the maximum field width. String input conversions store a null terminator ('\0') to mark the end of the input; the maximum field width does not include this terminator.

An optional type modifier character. For example, the l type modifier is used with integer conversions such as %d to specify that the corresponding pointer argument refers to a long int rather than a pointer to an int.

A conversion specifier that specifies the type of input conversion to be performed.

The conversion specifications in format are of two forms, either beginning with '%' or beginning with "%n$". The two forms should not be mixed in the same format string, except that a string containing "%n$" specifications can include %% and %*. If format contains '%' specifications then these correspond in order with successive pointer arguments. In the "%n$" form (which is specified in POSIX.1-2001, but not C99), n is a decimal integer that specifies that the converted input should be placed in the location referred to by the n-th pointer argument following format.
Conversions
The following type modifier characters can appear in a conversion specification:

h
Indicates that the conversion will be one of diouxX or n and the next pointer is a pointer to a short int or unsigned short int (rather than int).
hh
As for h, but the next pointer is a pointer to a signed char or unsigned char.
j
As for h, but the next pointer is a pointer to an intmax_t or a uintmax_t. This modifier was introduced in C99.
l
Indicates either that the conversion will be one of diouxX or n and the next pointer is a pointer to a long int or unsigned long int (rather than int), or that the conversion will be one of efg and the next pointer is a pointer to double (rather than float). Specifying two l characters is equivalent to L. If used with %c or %s the corresponding parameter is considered as a pointer to a wide character or wide-character string respectively.
L
Indicates that the conversion will be either efg and the next pointer is a pointer to long double or the conversion will be dioux and the next pointer is a pointer to long long.
q
equivalent to L. This specifier does not exist in ANSI C.
t
As for h, but the next pointer is a pointer to a ptrdiff_t. This modifier was introduced in C99.
z
As for h, but the next pointer is a pointer to a size_t. This modifier was introduced in C99.

The following conversion specifiers are available:

%
Matches a literal '%'. That is, %% in the format string matches a single input '%' character. No conversion is done, and assignment does not occur.
d
Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
D
Equivalent to ld; this exists only for backwards compatibility. (Note: thus only in libc4. In libc5 and glibc the %D is silently ignored, causing old programs to fail mysteriously.)
i
Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters that correspond to the base are used.
o
Matches an unsigned octal integer; the next pointer must be a pointer to unsigned int.
u
Matches an unsigned decimal integer; the next pointer must be a pointer to unsigned int.
x
Matches an unsigned hexadecimal integer; the next pointer must be a pointer to unsigned int.
X
Equivalent to x.
f
Matches an optionally signed floating-point number; the next pointer must be a pointer to float.
e
Equivalent to f.
g
Equivalent to f.
E
Equivalent to f.
a
(C99) Equivalent to f.
s
Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null character ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
c
Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating null byte is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.
[
Matches a non-empty sequence of characters from the specified set of accepted characters; the next pointer must be a pointer to char, and there must be enough room for all the characters in the string, plus a terminating null byte. The usual skip of leading white space is suppressed. The string is to be made up of characters in (or not in) a particular set; the set is defined by the characters between the open bracket [ character and a close bracket ] character. The set excludes those characters if the first character after the open bracket is a circumflex (^). To include a close bracket in the set, make it the first character after the open bracket or the circumflex; any other position will end the set. The hyphen character - is also special; when placed between two other characters, it adds all intervening characters to the set. To include a hyphen, make it the last character before the final close bracket. For instance, [^]0-9-] means the set "everything except close bracket, zero through nine, and hyphen". The string ends with the appearance of a character not in the (or, with a circumflex, in) set or when the field width runs out.
p
Matches a pointer value (as printed by %p in printf(3); the next pointer must be a pointer to a pointer to void.
n
Nothing is expected; instead, the number of characters consumed thus far from the input is stored through the next pointer, which must be a pointer to int. This is not a conversion, although it can be suppressed with the * assignment-suppression character. The C standard says: "Execution of a %n directive does not increment the assignment count returned at the completion of execution" but the Corrigendum seems to contradict this. Probably it is wise not to make any assumptions on the effect of %n conversions on the return value.

RETURN VALUE
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.
ERRORS
EAGAIN The file descriptor underlying stream is marked non-blocking, and the read operation would block.

EBADF
The file descriptor underlying stream is invalid, or not open for reading.
EILSEQ
Input byte sequence does not form a valid character.
EINTR
The read operation was interrupted by a signal.
EINVAL
Not enough arguments; or format is NULL.
ENOMEM
Out of memory.
ERANGE
The result of an integer conversion would exceed the size that can be stored in the corresponding integer type.

CONFORMING TO
The functions fscanf(), scanf(), and sscanf() conform to C89 and C99 and POSX.1-2001. These standard do not specify the ERANGE error.

The q specifier is the 4.4BSD notation for long long, while ll or the usage of L in integer conversions is the GNU notation.

The Linux version of these functions is based on the GNU libio library. Take a look at the info documentation of GNU libc (glibc-1.08) for a more concise description.
BUGS
All functions are fully C89 conformant, but provide the additional specifiers q and a as well as an additional behavior of the L and l specifiers. The latter may be considered to be a bug, as it changes the behavior of specifiers defined in C89.

Some combinations of the type modifiers and conversion specifiers defined by ANSI C do not make sense (e.g. %Ld). While they may have a well-defined behavior on Linux, this need not to be so on other architectures. Therefore it usually is better to use modifiers that are not defined by ANSI C at all, that is, use q instead of L in combination with diouxX conversions or ll.

The usage of q is not the same as on 4.4BSD, as it may be used in float conversions equivalently to L.
NOTES
The GNU C library supports a non-standard extension that causes the library to dynamically allocate a string of sufficient size for input strings for the %s and %a[range] conversion specifiers. To make use of this feature, specify a as a length modifier (thus %as or %a[range]). The caller must free(3) the returned string, as in the following example:

char *p;
int n;

errno = 0;
n = scanf("%a[a-z]", &p);
if (n == 1) {
printf("read: %s\n", p);
free(p);
} else if (errno != 0) {
perror("scanf");
} else {
fprintf(stderr, "No matching characters\n"):
}

As shown in the above example, it is only necessary to call free(3) if the scanf() call successfully read a string.

The a modifier is not available if the program is compiled with gcc -std=c99 or gcc -D_ISOC99_SOURCE (unless _GNU_SOURCE is also specified), in which case the a is interpreted as a specifier for floating point numbers (see above).

Since version 2.7, glibc also provides the m modifier for the same purpose as the a modifier. The m modifier has the following advantages:

*
It may also be applied to %c conversion specifiers (e.g., %3mc).
*
It avoids ambiguity with respect to the %a floating-point conversion specifier (and is unaffected by gcc -std=c99 etc.)
*
It is specified in the upcoming revision of the POSIX.1 standard.

SEE ALSO
getc(3), printf(3), setlocale(3), strtod(3), strtol(3), strtoul(3)
COLOPHON
This page is part of release 3.01 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at http://www.kernel.org/doc/man-pages/.


最近遇到个用C语言进行大文件处理的问题,以前没做过,希望各路高手给点...
答:识别换行字符。问:读取最后的一千行的单位名称。答:为了效率,打开文件后,就定位到倒数第1000个回车符的文件指针位置,进行读取。以换行符为分割来提取。

关于c语言文件读写问题和文件读写标志的疑问
先回答你第一个问题:因为fgets(out,5,fp)读取的是你输入字符串以后的字符,那是不确定的,所以会出现乱码,第二个问题:w+是将文件以读写方式打开,如果里面存有内容将会清零,以供写入 第三个问题:当你输入完字符以后文件的指针是指向末尾的,所以fget(out,5,fp)得到的是不是从头开始的字符,而是从最...

关于C语言读文件的问题,请教高人!
All functions are fully C89 conformant, but provide the additional specifiers q and a as well as an additional behavior of the L and l specifiers. The latter may be considered to be a bug, as it changes the behavior of specifiers defined in C89.Some combinations of the type modifiers and...

C语言文件的读写问题
简单的 fscanf(fp,"%s,%d", car[i].number, &car[i].in[0]); 是读不成功 的!必须用 fscanf(fp,"%[^,],%d", car[i].number, &car[i].in[0]); 的方法。下面是完整程序,假定输出\/输入量是3个结构。输出用carB, 输入用 car.include<stdio.h> define CHEPAIHAO 20 typede...

用c语言字符串文件读写问题
\\n"); exit(0); } if((fp=fopen(argv[1],"r"))==NULL) { printf("File open failed!\\n"); exit(0); } while((ch=fgetc(fp))!=EOF) { content[i++]=ch; } if((p=strstr(content,argv[2]))==NULL) { printf("-1\\n"); ...

C语言文件读取代码问题
include <stdio.h>#include <math.h>int main(){ FILE* fp; fp = fopen("data1.txt", "a+"); int i, j, flag, m; for (i = 2; i <= 1000; i++) { flag = 1; for (j = 2; j <= sqrt(i); j++) { if (i % j == 0) flag =...

C语言如何读写文件?
C语言读写文件有两种方式: 一种是文本方式,另一种是2进制方式。日文,中文,unicode, 都要用2进制方式。文件内容的编码和编码的转化,同一种编码的大端或小端编码,都要自己安排处理。C语言不管读写都要通过fopen函数来,其中mode参数可以控制以二进制打开还是以文本方式打开。fopen的函数原型:FILE *...

关于C语言读入txt文件问题
void myReadFile(char *pFile){ FILE *pf;pf = fopen(pFile,"rt");if ( NULL == pf ){ return;} while( !feof(pf) ){ Data aLine;memset(&aLine,0x0,sizeof(aLine));fscanf(pf,"%f,%f,%f,%f\\n",&aLine.x,&aLine.y,&aLine.z,&aLine.value);\/\/此处自己使用x,y,z,和...

如何用C语言读写文件
c语言读写文件程序:include "stdio.h"include <stdlib.h>main(){ FILE *fp1;\/\/定义文件流指针,用于打开读取的文件 FILE *fp2;\/\/定义文件流指针,用于打开写操作的文件 char text[1024];\/\/定义一个字符串数组,用于存储读取的字符 fp1 = fopen("d:\\\\a.txt","r");\/\/只读方式打开文件a....

C语言中指针读写文件,问什么记事本都是乱码,怎么改呢?
从代码看,在Windows平台是有大概率会乱码,假如你的商品信息数组里存放了换行就一定会乱码。主要问题在文件的打开方式不对,fread, fwrite函数最好以二进制模式打开文件,即打开方式加上b,即(rb, wb)。在unix\/Linux系统应该没问题。以下是问题解释:二进制和文本模式的区别 1.在windows系统中,文本...

修水县18581269125: C语言中 文件的读取 -
以垂丽申: 示例程序.//---------------------------------------------------------------------------#include <stdio.h>int main(void) {FILE *fp;double u[20];int i; fp=fopen("c:\\a.txt","r"); /*打开要读取数字的文件*/for (i = 0; i<20; i++) { /*打开的从文件中读取20个数字*...

修水县18581269125: C语言关于文件的读写问题? -
以垂丽申: 你可以这样:fscanf(pfile, "%s:", name);这样读取的时候只要读到:就会停下, 相当于是一个分隔符.

修水县18581269125: c语言如何读取任意格式的文件 -
以垂丽申: 对于程序来说,不管后缀名如何,文件分为两种类型:文本文件和二进制文件.C语言里有一系列文件操作函数.区分文本和二进制文件,需要在打开文件时设置不同的控制符mode的变量即可.fopen的函数原型:FILE * fopen(const char * path,...

修水县18581269125: C语言文件数据读取问题,求高人指点.. -
以垂丽申: 模式错了,应该是“a+”其次 return x跟exit()功能重复,但不会报错结构正确的话这程序就可以了建议你以后编程考虑写入失败动作,这样程序不会崩溃,调试会方便写

修水县18581269125: 关于用C语言读取一个文件 -
以垂丽申: #include <stdio.h> int main() { FILE *fp=fopen("temp.txt","r+");//打开文件 char ch=0; if (fp==NULL) { printf("Open File... Error!\n"); return -1; } for (int i=0;(ch=fgetc(fp))!=-1;i++)//以单个字符循环读取文件内存 { printf("%c",ch);//打印出内容 } fclose(fp);//关闭文件 return 0; }//一个例子

修水县18581269125: C语言 文件的读写的一些问题!! -
以垂丽申: while(!feof(fp) || c<11) { fread(* 有i? */,sizeof(struct student),1,fp);明显没有i...

修水县18581269125: c语言写入读取文件的问题!超级简单!求教大神!! -
以垂丽申: scanf(); 里面的\n删掉fprintf(); 里面不要用地址符 &而且你的主函数中data_out 和date_in 的顺序弄反了,还没开始写入文件,就因为文件无法打开而退出了

修水县18581269125: C语言文件读写问题 -
以垂丽申: 刚才仔细看了一下fwrite()函数说明,原来是这样的:fwrite()函数写入到文件的位置与文件的打开模式有关,如果是r+,则是从file pointer指向的地址开始写,替换掉之后的内容,文件的长度可以不变;如果是a+,则从文件的末尾开始添加,文件长度加大,而且是fseek函数对此函数没有作用.

修水县18581269125: 关于C语言中文件读取的问题 -
以垂丽申: 1)你的答案正确2)你的答案正确3)可以采用这种方法(伪码表示),r和c必须成对出现.while (next_char != *) { read struct r into its 4 memebers; read struct c into its 3 memebers;}4)应该是向后1个sturct占用的空间.

修水县18581269125: C语言读文件小问题 -
以垂丽申: 这是完整代码,本机运行满足你的说明要求.#include#include#define SIZE 1024const char* str1 = "\"2004/Feb/24\"";const...

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 星空见康网