簡體   English   中英

從C中的文本文件讀取

[英]Reading from a text file in C

我在從文件中讀取特定整數時遇到問題,我不確定為什么。 首先,我通讀了整個文件以找出它的大小,然后將指針重置為開始。 然后,我讀取了3個16字節的數據塊。 然后是1個20字節的塊,然后我想以整數讀取最后的1個字節。 但是,我必須以字符形式寫入文件,但我認為這不應該成為問題。 我的問題是,當我從文件中讀取它而不是整數值15時,它是49。我在ACII表中進行了檢查,它不是十六進制或八進制值1或5。我認為是正確的read語句為read(inF, pad, 1) 我確實知道一個整數變量是4個字節,但是文件中只剩下一個字節的數據,所以我只讀了最后一個字節。
我的代碼重現了該函數(看起來很多,但認為不是)

該代碼是

#include<math.h>
#include<stdio.h>
#include<string.h>
#include <fcntl.h>


int main(int argc, char** argv)
{
char x;
int y;
int bytes = 0;
int num = 0;
int count = 0;



num = open ("a_file", O_RDONLY);

bytes = read(num, y, 1);

printf("y %d\n", y);

return 0;
}

總結一下我的問題,當我從文本文件中讀取存儲15的字節時,為什么不能從整數表示中將其視為15? 任何幫助將不勝感激。 謝謝!

您正在讀取int的第一個字節(4個字節),然后將其整體打印。 如果要讀取一個字節,則還需要將其用作一個字節,如下所示:

char temp; // one-byte signed integer
read(fd, &temp, 1); // read the integer from file
printf("%hhd\n", temp); // print one-byte signed integer

或者,您可以使用常規int:

int temp; // four byte signed integer
read(fd, &temp, 4); // read it from file
printf("%d\n", temp); // print four-byte signed integer

請注意,這僅適用於具有32位整數的平台,並且還取決於平台的字節順序

您正在做的是:

int temp; // four byte signed integer
read(fd, &temp, 1); // read one byte from file into the integer
   // now first byte of four is from the file,
   // and the other three contain undefined garbage
printf("%d\n", temp); // print contents of mostly uninitialized memory

基於讀取功能,我認為它正在讀取整數的4個字節的第一個字節中的第一個字節,並且該字節未放置在最低字節中。 這意味着即使將其初始化為零,填充中其他3個字節的內容仍將存在(然后在其他字節中為零)。 我將讀取一個字節,然后將其轉換為整數(如果出於某種原因需要4字節整數),如下所示:

/* declare at the top of the program */
char temp;

/* Note line to replace  read(inF,pad,1) */
read(inF,&temp,1);

/* Added to cast the value read in to an integer high order bit may be propagated to make a negative number */
pad = (int) temp;

/* Mask off the high order bits */
pad &= 0x000000FF;

否則,您可以將聲明更改為無符號字符,這將處理其他3個字節。

read函數系統調用具有如下聲明:

 ssize_t read(int fd, void* buf, size_t count);

因此,您應該傳遞要在其中讀取內容的int變量的地址。 即使用

 bytes = read(num, &y, 1);

您可以從該鏈接查看 C中文件I / O的所有詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM