C - 在函数参数中声明一个文件
C - Declare a file in function parameters
所以这是我的问题:
int isopen()
{
int fd;
fd = open("myfile", O_RDONLY);
if (fd == 0)
printf("file opening error");
if (fd > 0)
printf("file opening success");
return(0);
}
int main(void)
{
isopen();
return(0);
}
我正在使用这段代码来检查打开命令是否有效,因为我刚刚开始研究如何使用它。
基本上这段代码工作得很好,但我想在我的函数 isopen 的参数中直接声明我想打开的文件。
我看到其他一些帖子使用 main 的 argc 和 argv,但我确实需要在我的函数 isopen 的参数中声明我的文件,而不是使用 argc 和 argv。
有可能吗?
谢谢你的帮助,我在这里很迷路。
你的问题不清楚,但也许你想要这个:
int isopen(const char *filename)
{
int fd;
fd = open(filename, O_RDONLY);
if (fd < 0) //BTW <<<<<<<<<<<< fd < 0 here !!
printf("file opening error");
else // else here
printf("file opening success");
return(0);
}
int main(void)
{
isopen("myfile");
return(0);
}
顺便说一句,此处的 isopen
函数仍然毫无用处,因为它只是打开文件并丢弃 fd
.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int isOpen(char *filename)
{
return open(filename, O_RDONLY);
}
int main()
{
printf("%d\n", isOpen("/home/viswesn/file1.txt"));
printf("%d\n", isOpen("file2.txt"));
return 0;
}
输出
viswesn@viswesn:~$ cat /home/viswesn/file1.txt
hello
viswesn@viswesn:~$
viswesn@viswesn:~$ cat /home/viswesn/file2.txt
cat: /home/viswesn/file2.txt: No such file or directory
viswesn@viswesn:~$
viswesn@viswesn:~$ ./a.out
3 <---------- File exist and it give file descriptor number '3'
STDIN-0, STDOUT-1, STDERR-2 are reserved and
next file opened will start with 3 and it keeps going
-1 <--------- File not found; so open gives -1 as error
所以这是我的问题:
int isopen()
{
int fd;
fd = open("myfile", O_RDONLY);
if (fd == 0)
printf("file opening error");
if (fd > 0)
printf("file opening success");
return(0);
}
int main(void)
{
isopen();
return(0);
}
我正在使用这段代码来检查打开命令是否有效,因为我刚刚开始研究如何使用它。
基本上这段代码工作得很好,但我想在我的函数 isopen 的参数中直接声明我想打开的文件。
我看到其他一些帖子使用 main 的 argc 和 argv,但我确实需要在我的函数 isopen 的参数中声明我的文件,而不是使用 argc 和 argv。
有可能吗?
谢谢你的帮助,我在这里很迷路。
你的问题不清楚,但也许你想要这个:
int isopen(const char *filename)
{
int fd;
fd = open(filename, O_RDONLY);
if (fd < 0) //BTW <<<<<<<<<<<< fd < 0 here !!
printf("file opening error");
else // else here
printf("file opening success");
return(0);
}
int main(void)
{
isopen("myfile");
return(0);
}
顺便说一句,此处的 isopen
函数仍然毫无用处,因为它只是打开文件并丢弃 fd
.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int isOpen(char *filename)
{
return open(filename, O_RDONLY);
}
int main()
{
printf("%d\n", isOpen("/home/viswesn/file1.txt"));
printf("%d\n", isOpen("file2.txt"));
return 0;
}
输出
viswesn@viswesn:~$ cat /home/viswesn/file1.txt
hello
viswesn@viswesn:~$
viswesn@viswesn:~$ cat /home/viswesn/file2.txt
cat: /home/viswesn/file2.txt: No such file or directory
viswesn@viswesn:~$
viswesn@viswesn:~$ ./a.out
3 <---------- File exist and it give file descriptor number '3'
STDIN-0, STDOUT-1, STDERR-2 are reserved and
next file opened will start with 3 and it keeps going
-1 <--------- File not found; so open gives -1 as error