[英]Segmentation Fault error using fgets function in c
我正在用C语言编写一个小代码,用于将特定字符串从一个文本文件复制到另一个文本文件中。 字符串在中间的某个地方。 我用C语言编写了一个代码。编译时,出现了段错误错误。
请帮忙。 我的代码如下:
int main()
{
FILE *fptr1, *fptr2;
char c;
char data[100];
// Open one file for reading
fptr1 = fopen(SPATH, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", SPATH);
exit(0);
}
// Open another file for writing
fptr2 = fopen(DPATH, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", DPATH);
exit(0);
}
// Read contents from file
while (!feof(fptr1))
{
fgets(data[20],29,fptr1);
printf("\n %s",data[20]);
fputs(data[29], fptr2);
}
printf("\nContents copied to %s", "file2.txt");
fclose(fptr1);
fclose(fptr2);
return 0;
}
而(!feof(file))总是错误的吗? ,因为feof(file)
在遇到EOF
之前不会测试为true
。 如果您使用以下方法控制循环:
while ( !feof (file) ) {
/* read statement */
/* write statement */
}
您的read语句将读取文件中的最后一行(或字符),保留下一个读取以触发EOF
,但是,当前读取成功并且未设置EOF
,您的写入操作成功。
接下来发生什么?
您测试feof (file)
仍然为false
,所以!feof (file)
测试为true
然后再次开始处理循环中的语句。 您的读取失败,因为读取指针位于EOF
之前,您具有无效的读取,然后您通过将不确定的值写入文件来调用write语句,以调用Undefined Behavior 。 触发“ 未定义行为 ”的程序,您的程序可以执行从显示成功完成到SEGFAULT或介于两者之间的任何操作。
相反,只需使用fgets
自身控制读取循环即可。 这样,只有fgets
成功,您才可以进入循环并将值写入文件,例如
#include <stdio.h>
#define MAXC 100 /* if you need a constant, #define one (or more) */
#define DPATH "file2.txt"
int main (int argc, char **argv) {
FILE *fptr1 = NULL, /* initialize all variables (good practice) */
*fptr2 = NULL;
char data[MAXC] = "";
/* open/validate file for reading (default stdin) */
fptr1 = argc > 1 ? fopen (argv[1], "r") : stdin;
if (fptr1 == NULL) {
fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
}
/* open/validate file for writing */
fptr2 = fopen (DPATH, "w");
if (fptr2 == NULL) {
fprintf (stderr, "error: file open failed '%s'.\n", DPATH);
return 1;
}
/* read contents from file */
while (fgets (data, sizeof data, fptr1)) { /* read 99-char blocks */
printf ("%s", data); /* (optional) output to stdout */
fputs (data, fptr2); /* write block to fptr2 */
}
printf ("\nContents copied to %s\n", DPATH);
fclose(fptr1);
if (fclose(fptr2) == EOF) /* always validate close-after-write */
perror ("fclose-fptr2");
return 0;
}
注意:不要在代码中使用幻数或硬编码值,相反,如果你需要的常量#define
它们(或数字常量,您还可以使用全局enum
来定义它们)。
*示例输入文件**
$ cat dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.
检查输出文件是否存在:
$ ls -al file2.txt
ls: cannot access 'file2.txt': No such file or directory
使用/输出示例
$ ./bin/fgets_copy_file <dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.
Contents copied to file2.txt
检查file2.txt
:
$ cat file2.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.
仔细检查一下,如果您还有其他问题,请告诉我。
就像其他回答者所说, fgets
的定义是:
char * fgets ( char * str, int num, FILE * stream );
data
是char*
类型,因此data[whatever]
是char
类型。 不好 您应该将其更改为data
。 您还可以在其他几个地方进行此操作。 也将它们更改为data
。
为了弄清楚问题出在fget中,您可以使用GDB之类的调试器:
$ gcc foo.c -g -o myprogram // Compile your program. '-g' means to use debug, and '-o myprogram' is the name of the program you want to make.
// LOTS of warnings that you should have read, which tell you you're probably using 'data' wrong
$ gdb myprogram
(gdb) break main
Breakpoint 1 at 0x40074e: file foo.c, line 7.
(gdb) run
Starting program: /home/anthonyd973/Desktop/myprogram
Breakpoint 1, main () at foo.c:7
7 {
(gdb) next
13 fptr1 = fopen(SPATH, "r");
(gdb) next
14 if (fptr1 == NULL)
(gdb) next
23 fptr2 = fopen(DPATH, "w");
(gdb) next
24 if (fptr2 == NULL)
(gdb) next
33 while (!feof(fptr1))
(gdb) next
35 fgets(data[20],29,fptr1);
(gdb) next
Program received signal SIGSEGV, Segmentation fault. // So the problem is at line 35, during 'fgets'.
(gdb) quit
A debugging session is active.
Inferior 1 [process 17669] will be killed.
Quit anyway? (y or n) y
$
修改您的while
循环,如下所示:
while (!feof(fptr1))
{
fgets(data, 99, fptr1);
fputs(data, fptr2);
}
请阅读有关fgets(),fputs()的文档。 随便键入man fgets
, man fputs
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.