【发布时间】:2012-10-29 04:39:50
【问题描述】:
我写了以下代码:
它应该接受一个文件名并创建它并写入它。什么都没发生。 我不明白为什么。我尝试搜索并看到类似的示例应该可以正常工作。 如果这很重要,我正在将 VirtualBox 与 Xubuntu 一起使用。
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <time.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#define SIZE_4KB 4096
#define FILE_SIZE 16777216
/*Generate a random string*/
char* randomStr(int length)
{
int i = -1;
char *result;
result = (char *)malloc(length);
while(i++ < length)
{
*(result+i) = (random() % 23) + 67;
if(i%SIZE_4KB)
*(result+i) = '\0';
}
return result;
}
void writeFile(int fd, char* data, int len, int rate)
{
int i = 0;
len--;
printf("Writing...\n");
printf("to file %d :", fd);
while(i < len)
{
write(fd, data, rate);
i += rate;
}
}
int main(int argc, char** argv)
{
int i = -1, fd;
char *rndStr;
char *filePath;
assert (argc == 2);
filePath = argv[1];
rndStr = randomStr(FILE_SIZE);
printf("The file %s was not found\n", filePath);
fd = open(filePath, O_CREAT, O_WRONLY);
writeFile(fd, rndStr, FILE_SIZE, SIZE_4KB);
return 0;
}
【问题讨论】:
-
您希望发生什么?
-
我希望你意识到
if(i%SIZE_4KB)表示if(i % SIZE_4KB != 0),即if(i不是SIZE_4KB)的倍数。 (目前,您将绝大多数rndStr设置为空字节。) -
学习使用所有警告和调试信息进行编译,即使用
gcc -Wall -g,改进您的代码直到没有给出警告,并使用gdb调试器(也许还有valgrind内存泄漏检测器) 来调试它。 -
@BasileStarynkevitch - 感谢您的建设性评论。我有时确实使用 dgb 进行调试,在这种情况下它对我没有帮助。但是我没有尝试使用 -Wall 命令(我是新手),这将是我在过去两年中用 c 语言编写的第二个程序。此评论将帮助我改进我的工作。
标签: c linux file system-calls