【发布时间】:2021-03-30 12:44:18
【问题描述】:
我写了一个代码来实现c中的文件锁定。在解决了错误和ignoring all the warnings haha 之后,我能够编译代码,但现在的问题是,当我尝试向文件中添加内容时,它显示分段错误。代码是:
#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");
this,在 switch case 的开头添加内容到文件。但无济于事。
【问题讨论】:
-
char c = getc(fd);c 应该是一个 int (加:不要重复自己...) -
好的,先生,我会做的。先生,错误出现在第一种情况下(我正在谈论的那个:()你能不能看看我的编辑并告诉它是否正确(我做了什么)@wildplasser
-
请修复编译器警告而不是忽略它们。当我编译程序时,我会收到实际指示错误的警告。您似乎混淆了
open与fopen并使用错误的参数调用其他函数。 -
没有像
#include <stdin.h>这样的头文件也可以看看fopen语法 -
我们不仅不是您的调试器,我们尤其不是交互式调试会话。
标签: c file-locking fcntl