C|使用指针变量和文件指针变量的基本步骤

C|使用指针变量和文件指针变量的基本步骤指针变量是C语言的灵魂,是C的效率和灵活性所在,也是安全问题所在。文件指针变量(FILE*)是一个指针结构体FILE的指针变量。

欢迎大家来到IT世界,在知识的湖畔探索吧!

指针变量是C语言的灵魂,是C的效率和灵活性所在,也是安全问题所在。文件指针变量(FILE*)是一个指针结构体FILE的指针变量。

1 指针变量 Pointer Variables

The rules for using pointer variables are similar to regular variables, except that you need to think about two types: the type of the pointer variable, and the type stored in the memory address to which the pointer variable points.

使用指针变量的规则与常规变量类似,只是需要考虑两种类型:指针变量的类型和存储在指针变量指向的内存地址中的类型。

1.1 Declare pointer variable 声明指针变量

First, declare a pointer variable using type_name *var_name:

使用type_name *var_name声明指针变量:

int *ptr;   // stores the memory address of an int (ptr "points to" an int)
char *cptr; // stores the memory address of a char (cptr "points to" a char)

欢迎大家来到IT世界,在知识的湖畔探索吧!

数形结合:

C|使用指针变量和文件指针变量的基本步骤

(声明后但暂未初始化的指针变量的值并不是空值或零值,有一个历史值或垃圾值,其指向不确定,其解引用未定义,其状态不确定。)

Note that although ptr and cptr are both pointers, they refer to different types:

请注意,尽管ptr和cptr都是指针,但它们指的是不同的类型:

The type of ptr is “pointer to int” (int *). It can point to a memory location that stores an int value.

ptr的类型是“指向int的指针”(int*)。它可以指向存储int值的内存位置。

The type of cptr is “pointer to char” (char *). It can point to a memory location that stores a char value.

cptr的类型是“指向字符的指针”(字符*)。它可以指向存储字符值的内存位置。

1.2 Initialize pointer variable 初始化指针变量

Next, initialize the pointer variable (make it point to something).

接下来,初始化指针变量(使其指向某物)。

Pointer variables store address values. A pointer should be initialized to store the address of a memory location whose type matches the type to which the pointer variable points. One way to initialize a pointer is to use the address operator (&) with a variable to get the variable’s address value:

指针变量存储地址值。应该初始化指针以存储其类型与指针变量指向的类型匹配的内存位置的地址。初始化指针的一种方法是将地址运算符(&)与变量一起使用,以获取变量的地址值:

欢迎大家来到IT世界,在知识的湖畔探索吧!int x;
char ch;
ptr = &x;    // ptr gets the address of x, pointer "points to" x
cptr = &ch;  // cptr gets the address of ch, pointer "points to" ch

数形结合:

C|使用指针变量和文件指针变量的基本步骤

(初始化后的指针变量的状态是确定的。)

Initialize ptr to the address of x and cptr to the address of ch (to point to x and ch, respectively).

将ptr初始化为x地址,将cptr初始化为ch地址(分别指向x和ch)。

Here’s an example of an invalid pointer initialization due to mismatched types:

以下是由于类型不匹配而导致指针初始化无效的示例:

cptr = &x;   // ERROR: cptr can hold a char memory location
             // (&x is the address of an int)

Even though the C compiler may allow this type of assignment (with a warning about incompatible types), the behavior of accessing and modifying x through cptr will likely not behave as the programmer expects. Instead, the programmer should use an int * variable to point to an int storage location.

尽管C编译器可能允许这种类型的赋值(带有关于不兼容类型的警告),但通过cptr访问和修改x的行为可能不会像程序员预期的那样。相反,程序员应该使用int*变量来指向int存储位置。

All pointer variables can also be assigned a special value, NULL, which represents an invalid address. While a null pointer (one whose value is NULL) should never be used to access memory, the value NULL is useful for testing a pointer variable to see if it points to a valid memory address. That is, C programmers will commonly check a pointer to ensure that its value isn’t NULL before attempting to access the memory location to which it points. To set a pointer to NULL:

还可以为所有指针变量分配一个特殊值NULL,该值表示无效地址。虽然null指针(其值为null)不应用于访问内存,但null值对于测试指针变量以查看其是否指向有效的内存地址非常有用。也就是说,C程序员通常会在尝试访问指针所指向的内存位置之前检查指针,以确保其值不为NULL。要将指针设置为NULL:

欢迎大家来到IT世界,在知识的湖畔探索吧!ptr = NULL;
cptr = NULL;

数形结合:

C|使用指针变量和文件指针变量的基本步骤

Initialize ptr and cptr to NULL.

将ptr和cptr初始化为NULL。

Any pointer can be given the special value NULL, which indicates that it doesn’t refer to any particular address. Null pointers should never be dereferenced.

任何指针都可以被赋予特殊值NULL,这表明它没有引用任何特定的地址。空指针永远不应取消引用。

1.3 Use the pointer variable 使用指针变量

Finally, use the pointer variable: the dereference operator (*) follows a pointer variable to the location in memory that it points to and accesses the value at that location:

最后,使用指针变量:解引用运算符(*)跟随指针变量,指向内存中它所指向的位置,并访问该位置的值:

/* Assuming an integer named x has already been declared, this code sets the
   value of x to 8. */
ptr = &x;   /* initialize ptr to the address of x (ptr points to variable x) */
*ptr = 8;   /* the memory location ptr points to is assigned 8 */

Dereference ptr to access the memory it points to (x, whose value is 8).

解引用ptr以访问其指向的内存(x,其值为8)。

数形结合:

C|使用指针变量和文件指针变量的基本步骤

(指针变量的操作可以区分为己操作和他操作,己操作是指指针变量自身的操作,常用于数组中元素指针的地址偏移,用于改变指向。他操作是指针对目标对象的操作,是指针变量的解引用用做左值或右值。)

2 FILE Pointer Variable 文件指针变量

To read or write a file in C, follow these steps:

要在C中读取或写入文件,请执行以下步骤:

2.1 Declare a FILE * variable 声明FILE *变量

FILE *infile;
FILE *outfile;

These declarations create pointer variables to a library-defined FILE * type. These pointers cannot be dereferenced in an application program. Instead, they refer to a specific file stream when passed to I/O library functions.

这些声明创建指向库定义的FILE *类型的指针变量。这些指针不能在应用程序中解引用。相反,它们在传递给I/O库函数时引用特定的文件流。

2.2 Open the file 打开文件

Associate the variable with an actual file stream by calling fopen. When opening a file, the mode parameter determines whether the program opens it for reading (“r”), writing (“w”), or appending (“a”):

通过调用fopen将变量与实际文件流相关联(相当于指针变量的初始化)。打开文件时,模式参数确定程序打开文件是为了读取(“r”)、写入(“w”)还是附加(“a”):

infile = fopen("input.txt", "r");  // relative path name of file, read mode
if (infile == NULL) {
    printf("Error: unable to open file %s\n", "input.txt");
    exit(1);
}
// fopen with absolute path name of file, write mode
outfile = fopen("/home/me/output.txt", "w");
if (outfile == NULL) {
    printf("Error: unable to open outfile\n");
    exit(1);
}

The fopen function returns NULL to report errors, which may occur if it’s given an invalid filename or the user doesn’t have permission to open the specified file (e.g., not having write permissions to the output.txt file).

fopen函数返回NULL以报告错误,如果给定的文件名无效或用户没有打开指定文件的权限(例如,没有对output.txt文件的写入权限),则可能会发生错误。

2.3 Using FILE* pointer variable 使用FILE*指针变量

Use I/O operations to read, write, or move the current position in the file:

使用输入/输出操作读取、写入或移动文件中的当前位置:

int ch;  // EOF is not a char value, but is an int.
         // since all char values can be stored in int, use int for ch
ch = getc(infile);      // read next char from the infile stream
if (ch != EOF) {
    putc(ch, outfile);  // write char value to the outfile stream
}

2.4 Close the file 关闭文件

use fclose to close the file when the program no longer needs it:

当程序不再需要文件时,使用fclose关闭文件:

fclose(infile);
fclose(outfile);

(对于动态申请的堆内存,使用完后同样需要使用free()手动释放。)

The stdio library also provides functions to change the current position in a file:

// to reset current position to beginning of file
void rewind(FILE *f);
rewind(infile);
// to move to a specific location in the file:
fseek(FILE *f, long offset, int whence);
fseek(f, 0, SEEK_SET);    // seek to the beginning of the file
fseek(f, 3, SEEK_CUR);    // seek 3 chars forward from the current position
fseek(f, -3, SEEK_END);   // seek 3 chars back from the end of the file

ref

https://diveintosystems.org/book/

-End-

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/49901.html

(0)

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们YX

mu99908888

在线咨询: 微信交谈

邮件:itzsgw@126.com

工作时间:时刻准备着!

关注微信