【发布时间】:2019-05-10 06:56:58
【问题描述】:
我有一个包含 3 行的文件,我想读取这个文件并将每一行保存为一个单独的字符串。 这是我尝试做的,它确实保存了第一行,但它通过保存第一行和第二行来覆盖它,我无法理解如何将每一行保存为单独的字符串,并且我也遇到了错误->
* 检测到堆栈破坏 *:/home/ubuntu/workspace/ex12.c.o 已终止 中止
#include <stdio.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
#include <unistd.h>
extern int errno;
int main( int argc, char *argv[] ) {
char *path1;
char firstline[80];
char secondline[80];
char thirdline[80];
printf("Program name %s\n", argv[0]);
if( argc == 2 ) {
printf("The path of the config file that you supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
int fd1 = open(argv[1], O_RDONLY | O_CREAT);
if (fd1 ==-1)
{
// print which type of error have in a code
printf("Error Number % d\n", errno);
// print program detail "Success or failure"
perror("Program");
exit(EXIT_FAILURE);
}
else {
char c;
int i=0;
while ((read(fd1, &c, 1) == 1) )
{
firstline[i++]=c;
if(c=='\n')
{
//printf("end of line");
printf("%s",firstline);
}
}
}
int close(int fd1);
return 0;
}
注意:我不想使用 fopen、fgets、sscanf 或 getline。 任何帮助将不胜感激
【问题讨论】:
-
首先,发布格式良好、缩进良好的代码总是值得的。没有人愿意阅读之字形。其次,
int close(int fd1);是一个函数原型。它不是函数调用,也不会关闭任何文件。第三,你总是读到firstline。为什么你希望它不会被覆盖?最后,不要在迭代结束时重置i并用完数组边界。 -
例如您必须在第 1 行结束后退出 while 循环
break;。另外i没有结尾,第一行很容易溢出! -
贴出的代码无法编译!即使在猜测了您的实际代码包含哪个头文件之后,编译器仍然会发出一些关于未使用变量等的警告。请修复发布的代码,以便它可以干净地编译,
-
@Tom Kuschel 但如果我在第 1 行结束后中断,我将无法获得第 2 行和第 3 行,我想像第 1 行一样将它们作为 2 个单独的字符串获得。
-
@user3629249 我已经添加了头文件,现在应该可以编译了
标签: c file operating-system system-calls