我不是C天才。所以..首先对我的愚蠢问题感到抱歉。我有一个 .txt 文件或 .dta(随便),我想用 C 语言读取它。我想获取 txt 的数字,格式化为两列和 x 行,并将所有数据存储到一个矩阵中(或向量)。
据了解,我正在使用此代码:
/*
** File FILE_3.C
**
** Illustrates how to read from a file.
**
** The file is opened for reading. Each line is successively fetched
** using fgets command. The string is then converted to a long integer.
**
** Note that fgets returns NULL when there are no more lines in the file.
**
** In this example file ELAPSED.DTA consists of various elapsed times in
** seconds. This may have been the result of logging the time of events
** using an elapsed time counter which increments each second from the
** time the data logger was placed in service.
**
** Typical data in elapsed.dta might be;
**
** 653 75
** 142 90
** 104 10
** 604 10
** 124 12
**
*/
#include <stdio.h> /* required for file operations */
FILE *fr; /* declare the file pointer */
main()
{
int n;
long elapsed_seconds;
char line[80];
fr = fopen ("elapsed.txt", "rt"); /* open the file for reading */
/* elapsed.dta is the name of the file */
/* "rt" means open the file for reading text */
while(fgets(line, 80, fr) != NULL)
{
sscanf (line, "%ld", &elapsed_seconds);
/* convert the string to a long int */
printf ("%ld\n", elapsed_seconds);
}
fclose(fr); /* close the file prior to exiting the routine */
} /*of main*/
你能帮助我吗?
感谢您的回答