C 编程文件 I/O

标签 c file-io

我试图从一个文本文件中读取并写入一个文本文件,但每次执行代码时,文本文件都没有发生任何事情。 “什么也没发生”是指程序不会读取我的输入文件,并且没有数据导出到我的输出文件中。有人可以指出为什么它不起作用吗?感谢您提前提供的任何帮助。这是我的代码:

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

FILE *inptr, *outptr; 

int main() {
    int a, b, c;
    inptr = fopen("trianglein.txt","r"); //Initialization of pointer and opening of file trianglein.txt
    outptr = fopen("triangleout.txt","w"); //Initialization of pointer and opening of file triangleout.txt

    while((fscanf(inptr,"%d %d %d",&a, &b, &c))!= EOF){  
        fprintf(outptr,"\n%2d %2d %2d\n",a,b,c); 
        if(a+b>c && b+c>a && c+a>b){
            fprintf(outptr, "This is a triangle.\n"); 
            if(a !=b && b !=c && a!=c){ 
                fprintf(outptr, "This is a scalene triangle.\n");
                if(a==b && a==c && c==b){
                    fprintf(outptr, "This is an equilateral triangle.\n");
                    if(a*a+b*b==c*c || b*b+c*c==a*a || a*a+c*c==b*b){
                        fprintf(outptr, "This is a right trianlge.\n");
                    }
                }
            } 
        }
    }

    return 0;
}

trianglein.txt内容:

10 12 15
2 3 7
3 4 5
6 9 5
6 6 6
6 8 10
7 7 9

最佳答案

多个问题。

首先,您需要通过测试 NULL 来检查 inptr 和 outptr 是否有效。

其次,fscanf 可以返回 EOF、0 或 > 0。

如果您的输入文件不包含有效的输入。

还有一个问题是,你可以成功读取 3 个整数,或者 2 个整数或 1 个整数,并且 a、b 和 c 的值只能选择性设置。

如果输入上没有发生转换,则返回零值,在这种情况下,while 循环将退出。

另请记住,使用 scanf 样式函数,此输入将成功并返回值 1。

"1rubbish"

我认为您可能想要的是如下内容:

// Somewhere near the top
#include <stderr.h>
// ... other includes

const char* inname = "trianglein.txt";
const char* outname = "triangleout.txt";

// Any other stuff


// Inside main...

// Initialization of pointer and opening of file trianglein.txt
if ((inptr = fopen(inname,"r")) == 0){
  fprintf(stderr, "Error opening file %s: %s", inname, strerror(inname));
  return -1;
}

// Initialization of pointer and opening of file triangleout.txt
if ((outptr = fopen(outname,"w")) == 0){
  fprintf(stderr, "Error opening file %s: %s", outname, strerror(outname));
  return -1;
}


int result;
while(true){
  result = fscanf(inptr,"%d %d %d",&a, &b, &c);
  if (result == EOF)
    break;

  if (result < 3)  // Ignore incomplete lines
    continue;

  // do the normal stuff
}  

关于C 编程文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16642208/

相关文章:

c - 使用 fgets 和 strstr 产生意外结果

c - 读取文件以在 c 中创建矩阵

java - 将xml文件注入(inject)spring bean

c - 带有 BIO API 的 OpenSSL EVP_aes_128_gcm

c - 使用冒泡排序在 C 中对二维数组进行排序

c - 为什么这个定义指令似乎不起作用?

c++将文件连接返回给成员,因此可以由同一类的其他方法使用

java - 在项目根文件夹中找不到文件

java - 在 Java SE 6 中 move 文件并进行错误处理

c - 在 C 代码中使用 libavformat,未定义的 x86_64 符号