gpt4 book ai didi

c - 如何编写代码来区分现有文件或新生成的文件中是否存在 '0'

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:11 25 4
gpt4 key购买 nike

我一直在研究代码:

    1.检查“sample.txt”是否存在,如果不存在,则生成一个新文件,
    2。如果文件已经存在,检查第一行是否有单个'0'。如果不是,截断并写入'0'

以下是我到目前为止所写的内容。但是 iszeroOrnewfile 总是变成 0 所以不要进入不同的情况。我处理这个问题正确吗?

   #include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define buf 128
int main (int argc, char** argv)
{
int fd;
char buff[buf]={0} ;
int iszeroOrnewfile=1;
int iszero=0;
if(!(argv[0]>0))
printf("insert positive integer");
fd = open("./sample.txt",O_RDWR|O_CREAT);
pread ( fd,buff,buf,0);
for (int i=0;i<buf;i++)
{
if((0 != buff[i]) || ('0' != buff[i]) )
{ iszeroOrnewfile = 0;}
if('0' == buff [i]);
{ iszero = 1;}

}
if (iszeroOrnewfile == 1 )
{
if (iszero !=1)
write(fd, "0",strlen("0"));
}
else if(iszeroOrnewfile ==0)
{
truncate ("./sample.txt" , 0);
write(fd, "0",strlen("0"));
}

}

最佳答案

以下代码可能有用:

#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#define buf 128


int main (int argc, char** argv)
{
int fd;
char buff[buf]={0} ;
int iszeroOrnewfile=1;
int iszero=0;
int isFileCreated = 0;
int len = 0;
int i;
if(!(argv[0]>0))
printf("insert positive integer");
fd = open("./sample.txt",O_RDWR);
if(fd==-1 && errno==ENOENT)
{
//File dosen't exists
isFileCreated = 1;
fd = open("./sample.txt",O_RDWR|O_CREAT);
write(fd, "0",strlen("0"));
}
else
{
len = pread ( fd,buff,buf,0);
for (i=0;i<len;i++)
{
if((0 == buff[i]) || ('0' == buff[i]) )
{
iszero = 1;
break;
}
}
if(len==-1 || iszero)
{
truncate ("./sample.txt" , 0);
write(fd, "0",strlen("0"));
}
}
return 0;
}

关于c - 如何编写代码来区分现有文件或新生成的文件中是否存在 '0',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47268180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com