C编程涉及文件和结构

时间:2011-01-11 04:15:34

标签: c

如何使用fgetc从文件中读取负数?

7 个答案:

答案 0 :(得分:4)

fgetc一次只能读取一个字符。如果您尝试从文件中读取负数 - 或任何数字 - 请使用fscanf

#include <stdio.h>

main()
{
  int v;
  fscanf (stdin, "%d", &v);
  printf ("v = %d\n", v);
}

答案 1 :(得分:1)

如果标题中的“结构”意味着二进制,那么你可能想要使用fread(),但是如果你真的在追逐存储在二进制文件中的整数布局的问题,你可以使用fgetc ()。

此代码显示如何使用union将一系列读取字节映射回整数。

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

union Integer
{
    int intPart_;
    char charPart_[4];
};


int main(int argc, char* argv[])
{
    FILE* pFile = fopen("integerFile.dat", "w");

    int intWritten = -257;
    size_t bytesWritten = fwrite(&intWritten, 1, sizeof(int), pFile);
    assert(bytesWritten == sizeof(int));
    fclose(pFile);

    pFile = fopen("integerFile.dat", "r");
    int intRead = 0;
    size_t bytesRead = fread(&intRead, 1, sizeof(int), pFile);
    assert(bytesRead == sizeof(int));
    printf("%d\n", intRead);
    fclose(pFile);

    pFile = fopen("integerFile.dat", "r");
    Integer intToRead;
    for(int i = 0;
        i != sizeof(int);
        ++i)
    {
        int byteRead = fgetc(pFile);
        intToRead.charPart_[i] = byteRead;
        printf("%d\n", byteRead );
    }
    printf("%d\n", intToRead.intPart_);


    fclose(pFile);


    return 0;
}

答案 2 :(得分:0)

编号如何编码?

如果是ASCII,请记住它需要多个字符。您可以为它编写循环,但您可能会发现fscanf更多帮助。

如果是二进制数据,请记住fgetc只会读取8位 - 再次,您需要考虑其他函数来有效地执行此操作。

这里的要点是,除非你这样做只是为了证明你可以fgetc可能是错误的答案。也许fgets

答案 3 :(得分:0)

fgetc()将字符解释为“unsigned char”,但将其强制转换为int(但在文件末尾返回EOF,即-1)。

如果您的源文件包含一些带符号值的表示,那么您需要对其进行解码。

答案 4 :(得分:0)

'0'的ascii值为0x30,'1'为0x31 ......到目前为止...... 假设您的文件中只有一个数字:

   FILE * pFile;
   int c, n = 0;
   bool negative;
   pFile=fopen ("myfile.txt","r");
   if (pFile==NULL){
      perror("Error opening file");
   }else{
        c = fgetc (pFile);
        negative = (c == '-');
        do {
          c = fgetc (pFile);
          if (c>=0x30 && c<=0x39) {
         n = n*10 + (c-0x30);
       }
        } while (c != EOF);
        fclose (pFile);
   }
   if(negative==true) n=n*-1;
   printf ("Your number: %d\n",n);

答案 5 :(得分:0)

我和Charlie在一起,有更好的方法来做这个,而不是需要多次调用fgetc,但是如果你坚持使用该函数,你需要运行一个循环来评估每个char 。它还取决于数据的编码方式。如果它是ascii(因为使用返回char的func意味着),你将检查第一个char是否为“ - ”,然后将每个后续char转换为int,同时将atoi(con​​st char *)转换为int,并乘以在将新值添加到每个迭代之前,每个迭代的结果值为10。更好的方法是读取几个字符(使用fgets或其他东西),然后使用atoi(con​​st char *)转换char *。也许如果你更清楚地描述了你想要做的事情,可以提供更好的答案。请注意,如果您的数据格式不符合您指定的格式,则使用fscanf将失败。但fscanf确实是你解决这个问题的答案。

答案 6 :(得分:0)

如果没有上溢/下溢检查,您可以使用fscanf WITH返回值检查:

#include <stdio.h>

int main()
{
  int v;
  if( 1==fscanf(yourfilepointer, "%d", &v) )
    printf ("v = %d\n", v);
  else
    fputs("error on reading v",stderr);
  return 0;
}