gpt4 book ai didi

c - 在 C 中读取文件中的 double

转载 作者:行者123 更新时间:2023-11-30 16:43:35 26 4
gpt4 key购买 nike

我试图从 C 语言的文件中读取 double ,但事实证明这是一场噩梦。当我想读取整数或字符时,我似乎没有遇到任何问题,但是 double 似乎很难使用。

所以,假设我有一个包含两列和四行 double 字的文件,我想要两个 vector 来保存每列中的所有数据。我的代码是:

int main(void){

double v1[4],v2[4];
FILE *f;
int i;

f=fopen("hola.rtf","r");
if(f==NULL){
printf("Error fitxer!\n");
exit(1);
}
for(i=0;i<4;i++){
fscanf(f,"%le",&v1[i]);
fscanf(f,"%le",&v2[i]);
printf("%le %le\n",v1[i],v2[i]);
}
fclose(f);
return 0;

但是打印的所有值都是 0...有什么想法/提示吗?

谢谢:)

最佳答案

您没有检查 fscanf() 的返回值,因此您不知道它是否转换(并读取)数据。

此外,double 的说明符对于 printf() %e (或 %f%g ,具体取决于您想要的格式); %le不是 C 中的有效说明符,因此如果您的程序打印任何内容,那是因为您的编译器或 C 库接受 %le 。 (不过,无论它理解为什么格式,都可能不是 double 。)

<小时/>

以下是您应该如何阅读 double :

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

#define COUNT 4

int main(void)
{
const char *filename = "hola.rtf";
FILE *input;
double v1[COUNT], v2[COUNT];
int i;

input = fopen(filename, "r");
if (!input) {
fprintf(stderr, "Cannot open %s: %s.\n", filename, strerror(errno));
return EXIT_FAILURE;
}

for (i = 0; i < COUNT; i++) {
if (fscanf(input, " %le %le", &(v1[i]), &(v2[i])) != 2) {
fprintf(stderr, "Invalid data in %s.\n", filename);
fclose(input);
return EXIT_FAILURE;
}

printf("Read %e and %e from %s.\n", v1[i], v2[i], filename);
}

if (ferror(input)) {
fclose(input);
fprintf(stderr, "Error reading %s.\n", filename);
return EXIT_FAILURE;
}
if (fclose(input)) {
fprintf(stderr, "Error closing %s.\n", filename);
return EXIT_FAILURE;
}

printf("All %d pairs of doubles read successfully.\n");

return EXIT_SUCCESS;
}

许多程序员认为他们可以稍后再添加错误检查。这是不切实际的;他们通常最终得到的是没有或很少有错误检查的代码。然而,作为用户,您难道不想知道程序何时出现故障并产生垃圾而不是正常结果吗?我确实这样做,我认识的所有使用代码进行实际工作的人也是如此。这是一个需要养成的重要习惯,因为如果你学会不这样做,以后就很难学会这样做。

错误检查的级别当然可以讨论。我相信这里的许多成员都会考虑ferror()检查并检查 fclose() 的结果为“不必要”。确实,它们在正常、典型的操作中不会失败。程序员有可能永远不会看到它们中的任何一个失败。然而,当它们确实失败时——比如,有人最终在 FUSE 文件系统上运行你的代码,该文件系统可以在关闭时报告错误——检查可能意味着大量垃圾和出现问题的早期警告之间的区别。

如果您碰巧同意我的观点(关于半偏执的错误检查是良性的,有时对用户非常有用),请考虑您的代码的以下变体,它从命令行指定的文件中读取所有双对到动态分配的数组:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

typedef struct {
double x;
double y;
} vec2d;

/* Read all 2D vectors from stream 'input',
into a dynamically allocated array.
(Similar to POSIX.1 getline(), but with double vectors.)
If *dataptr is not NULL, and *sizeptr > 0,
it will initially be used (but reallocated if needed).
Returns the number of vectors read,
or 0 with errno set if an error occurs.
*/
size_t vec2d_readall(FILE *input, vec2d **dataptr, size_t *sizeptr)
{
vec2d *data;
size_t size;
size_t used = 0;

if (!input || !dataptr || !sizeptr) {
/* At least one of the parameters is NULL. */
errno = EINVAL;
return 0;
}

if (ferror(input)) {
/* input stream is already in error state. */
errno = EIO;
return 0;
}

if (!*dataptr || !*sizeptr) {
/* *dataptr is NULL, or *sizeptr == 0,
so we initialize them to empty. */
*dataptr = NULL;
*sizeptr = 0;
}
data = *dataptr;
size = *sizeptr;

while (1) {

if (used >= size) {
/* We need to grow the data array. */

/* Simple allocation policy:
allocate in sets of roughly 1024 vectors. */
size = (used | 1023) + 1021;
data = realloc(data, size * sizeof *data);
if (!data) {
/* Realloc failed! */
errno = ENOMEM;
return 0;
}

*dataptr = data;
*sizeptr = size;
}

if (fscanf(input, " %lf %lf", &(data[used].x), &(data[used].y)) != 2)
break;

/* One more vector read successfully. */
used++;
}

/* If there was an actual I/O error, or
the file contains unread data, set errno
to EIO, otherwise set it to 0. */
if (ferror(input) || !feof(input))
errno = EIO;
else
errno = 0;

return used;
}

因为vec2d_readall()函数总是设置errno (如果没有发生错误,则为 0),使用上述函数从标准输入中读取所有 double 对作为 2D vector 非常简单:

int main(void)
{
vec2d *vectors = NULL;
size_t num_vectors = 0;
size_t max_vectors = 0;

size_t i;

num_vectors = vec2d_readall(stdin, &vectors, &max_vectors);
if (errno) {
fprintf(stderr, "Standard input: %s.\n", strerror(errno));
return EXIT_FAILURE;
}

printf("Read %zu vectors from standard input,\n", num_vectors);
printf("with memory allocated for up to %zu vectors.\n", max_vectors);

for (i = 0u; i < num_vectors; i++)
printf("%f %f\n", vectors[i].x, vectors[i].y);

return EXIT_SUCCESS;
}

在写作上花费了一点额外的努力vec2d_readall()简化了我们的main()很多。另外,如果我们发现需要类似的函数来读取 3D vector ,我们只需要添加 typedef struct { double x; double y; double z } vec3d; ,并对 vec2d_readall() 进行一些非常小的更改将其变成 vec3d_readall() .

最重要的是,我们可以信赖vec2d_readall()如果数据存在任何类型的问题,则失败。我们可以添加错误报告,而不仅仅是 break;跳出循环。

如果您想知道 getline() 在评论中提到,它是一个 POSIX.1-2008 标准函数,允许 POSIXy 系统中的 C 程序员读取无限长度的输入行。它类似于 fgets() ,但具有动态内存管理。

关于c - 在 C 中读取文件中的 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45142860/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com