Hello, you need to write a function on C that will open a specific file and add a number 1 more than the previous one. the function should read the last line and add the following number to the new line. For example, there were already numbers (1, 2 (from a new line)) and the number 3 should appear. Either these numbers have not yet been in the file.
My attempts to create something:
#include <stdio.h> #include <string.h> #include <stdlib.h> int id(void) { int i; char buff[] = "00001"; char delim[] = "|"; char *word; FILE *f; if ((f = fopen("bd2.txt", "a+"))==NULL) { fprintf(f, "%s\n", "00000");//но.....нет.(не выполняет.) } f = fopen("bd2.txt", "a+");//Для перехода в конец. if(!f) puts("ERROR"), exit(1); word = strtok(buff, delim);//В нашей ситуации не нужно Num = atoi (word); //Вот только atoi надо использовать с f как-то fprintf(f, "%s\n ", word); word = strtok(NULL, delim); fclose(f); return 0; } // Runs only buff, tried to do something through atoi, but my program // doesn’t work further.
// In this program there will be an infinite loop. incorrectly set // variables (Most likely) But I do not know how to fix it.
#include <stdio.h> #include <string.h> #include <stdlib.h> //У программы бесконечный цикл, скорее всего. Ибо зависла. int main(void) { char buff[] = "0"; char delim[] = "|"; //char *word; int Num=0;//Список ID с 0 и по возрастающей.Дважды обьявляю? int i=0;//Чтоб программа потом выполнялась только 1 раз int k=1;//Аналогично FILE *f; if ((f = fopen("bd2.txt", "a+"))==NULL) { fprintf(f, "%d\n", Num);//но.....нет. } f = fopen("bd2.txt", "a+");//Для перехода в конец. if(!f) puts("ERROR"), exit(1); // word = strtok(buff, delim);//оставит до разделителя инфу. Num = atoi (buff); if (Num=0)//Хотел сделать на случай самого первого ID { for(int Num=0; Num<1; Num++) fprintf(f, "%d\n ", Num); fclose(f); } else //И на случай остальных ID, основная программа. { //Неверный цикл, я неправильно написал.(переменная k) for(int Num=k; Num>=1; i++) fprintf(f, "%d\n ", Num); Num=Num+1; } // word = strtok(NULL, delim); k=k+1; fclose(f); return 0; }
if ((f = fopen("bd2.txt", "a+"))==NULL) { fprintf(f, "%d\n", Num);//но.....нет. }if ((f = fopen("bd2.txt", "a+"))==NULL) { fprintf(f, "%d\n", Num);//но.....нет. }- Translated into Russian: if the file is NOT opened, we write it into it ... - Harry