Jam*_*ade -1 c file raspberry-pi
我是C语言编程的新手,我正在使用C编译器为Raspberry Pi编程.我想要做的就是创建一个函数,该函数将String作为参数并将其保存为特定位置的文本文件.我想检查该文件位置以查看存在的文件,并将新文件保存到该文件夹,并以1的增量添加到文件名中.
例如,文件夹包含:
TestFile1 TestFile2
我希望能够创建保存为TestFile3的新文件.
这是我到目前为止的代码,想知道我是否在正确的位置并获得任何提示,请:
void WriteToFile(unsigned char *pID)
{
printf("Writing to file. . . . .\n");
/* Checking to see how many files are in the directory. */
int *count = 0;
DIR *d;
struct dirent *dir;
d = opendir("table_orders");
if(d)
{
while((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
count = count + 1; // Adds 1 to count whenever a file is found.
}
closedir(d);
}
char str[sizeOf(count)]; // Creates string.
sprintf(str, "%d", count); // Formats count integer into a string.
File *f = fopen("table_orders/Order " + str + ".txt", "a"); // Creates new file.
if(f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
fprintf(f, "Order: %s \n", pID);
fclose(f);
printf("The Order %s has been written to the file\n", pID);
}
Run Code Online (Sandbox Code Playgroud)
int fd = open( "filename", O_RDWR | O_CREAT | O_EXCL, 0644 );
Run Code Online (Sandbox Code Playgroud)
没有其他东西是原子的 - 另一个进程可以在任何存在检查和文件的实际创建之间创建文件.