问题描述
我写了一段代码在c中实现文件锁定。解决错误和 ignoring all the warnings
哈哈后,我能够编译代码,但现在问题是,当我尝试向文件添加内容时,它显示分段错误。代码是:
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
char data[1000],ch;
int cont;
int main(int argc,char **argv) {
if (argc > 1) {
int fd = fopen(argv[1],"w");
if(fd == -1) {
printf("Unable to open the file\n");
exit(1);
}
static struct flock lock;
lock.l_type = F_WRLCK;
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
lock.l_pid = getpid();
int ret = fcntl(fd,F_SETLKW,&lock);
printf("Return value of fcntl:%d\n",ret);
printf("\n\n\tOperations you can perform here:\n\t\n");
printf("\n\t1.ADD TO FILE\n\t2.DELETE THE FILE\n\t3.PRINT CONTENTS OF FILE\n\t4.EXIT");
printf("\n\tEnter your choice: ");
scanf("%d",&cont);
switch(cont)
{
case 1:
printf("Enter contents to store in file : \n");
fgets(data,1000,stdin);
fputs(data,fd);
printf("Data added to the file successfully");
break;
case 2:
remove(fd);
break;
case 3:
int c = getc(fd);
while (c != EOF)
{
printf("%c",c);
c = getc(fd);
}
case 4:
exit(0);
}
}
}
我什至尝试过
fclose(fd); fd = fopen("advisory.txt","a");
这个,在 switch case 的开头添加内容到文件。但无济于事。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)