Inserting a text into a specific line - c

I am trying to create a function which inserts texts between lines according to the user input. The user has to specify the line number and the index in order to insert his line.
Currently, I have managed to insert the text before the line, but I can't insert it into the line "index".
Does anyone know how to insert according to the index number?
PS. I am still starter at C programming. I know there are too many times that the file is opened and closed!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void inserttext(void);
main ()
{
inserttext();
}
void inserttext(void)
{
FILE *file1,*file2;
char *f = malloc(sizeof(char)), *t = malloc(sizeof(char));
int l,i,r,y,n,index,nl=0;
printf("Enter a text file name: ");
scanf("%s",f);
if (access(f,F_OK)!=-1)//if the text file exists
{
file1=fopen(f, "r+");
file2=fopen("f2.txt", "w+");
printf("\nThe file before editing:\n\n");
while((n=fgetc(file1))!=EOF)// to show the contents of the file before the edit
{
putchar(n);
}
fclose(file1);
fclose(file2);
if(access(f,W_OK)!=-1)//if the file has the write permission
{
file1=fopen(f, "r+");
file2=fopen("f2.txt", "w+");
printf("\n\nPlease enter your text: \n");
scanf(" %[^\n]s ",t);
printf("Specify the line number where you want to insert: ");
scanf("%d", &l);
printf("\nindex:\n");
scanf("%d", &index);
while((r=fgetc(file1))!=EOF)//copying file1 contents into file2 contents
{
fputc(r,file2);
if(r == '\n' && ++nl == l){
fprintf(file2, "%s ", t);//adding the inserted text
}
}
fclose(file1);
fclose(file2);
file1=fopen(f, "w+");
file2=fopen("f2.txt", "r");
while((y=fgetc(file2))!=EOF){
fputc(y,file1);
}
fclose(file2);
fclose(file1);
remove("f2.txt");
file1=fopen(f, "r");
printf("\n");
while((i=fgetc(file1))!=EOF)//showing the result after inserting
{
putchar(i);
}
fclose(file1);
free(f);
free(t);
}
else{
printf("\n%s text file does not have the Write Permission!", f);
free(f);
free(t);
return;
}
}else{
printf("file doesn't exits!\n");
}
}

This uses ftell() and fseek() to save the file position at the start of the selected line, read the length of the line and return to the start of the line.
The user is prompted to input an index into the line less than the line length.
I did get a segmentation fault with the original malloc's for *t and *f. I tried some longer inputs, so this allocates 100 characters to each pointer.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void inserttext(void);
int main ()
{
inserttext();
return 0;
}
void inserttext(void)
{
FILE *file1,*file2;
char *f = malloc(100), *t = malloc(100);
int l,i,r,y,n,index,nl=0;
int linelength = 0;;
long offset = 0;
printf("Enter a text file name: ");
scanf("%99s",f);
if (access(f,F_OK)!=-1)//if the text file exists
{
file1=fopen(f, "r+");
file2=fopen("f2.txt", "w+");
printf("\nThe file before editing:\n\n");
while((n=fgetc(file1))!=EOF)// to show the contents of the file before the edit
{
putchar(n);
}
fclose(file1);
fclose(file2);
if(access(f,W_OK)!=-1)//if the file has the write permission
{
file1=fopen(f, "r+");
file2=fopen("f2.txt", "w+");
printf("\n\nPlease enter your text: \n");
scanf(" %99[^\n]",t);
printf("Specify the line number where you want to insert: ");
scanf("%d", &l);
while((r=fgetc(file1))!=EOF)//copying file1 contents into file2 contents
{
fputc(r,file2);
if(r == '\n' && ++nl == l){
offset = ftell ( file1);//save location in file
while ( ( r = fgetc ( file1)) != '\n' && r != EOF) {
linelength++;//count characters in line
}
fseek ( file1, offset, SEEK_SET);//seek back to start of line
//get index where to insert text
do {
printf("\nindex(less than %d):\n", linelength);
if ( ( scanf("%d", &index)) != 1) {
scanf ( "%*[^\n]");//input not an integer. clear buffer
index = linelength;
}
} while ( index >= linelength || index < 0);
while ( index) {
r = fgetc ( file1);
fputc(r,file2);
index--;
}
fprintf(file2, "%s ", t);//adding the inserted text
}
}
printf("\nDONE:\n");
fclose(file1);
fclose(file2);
file1=fopen(f, "w+");
file2=fopen("f2.txt", "r");
while((y=fgetc(file2))!=EOF){
fputc(y,file1);
}
fclose(file2);
fclose(file1);
remove("f2.txt");
file1=fopen(f, "r");
printf("\n");
while((i=fgetc(file1))!=EOF)//showing the result after inserting
{
putchar(i);
}
fclose(file1);
free(f);
free(t);
}
else{
printf("\n%s text file does not have the Write Permission!", f);
free(f);
free(t);
return;
}
}else{
printf("file doesn't exits!\n");
}
}

Related

How to print the text from a file if the line number is given?

I want to give input as line number and get output as the corresponding text for that line number in a text file.
Sample text file:
Hi this is Stefen
Hi How are you
Example input:
Enter the line number:2
Expected Output:
Hi How are you
My program is:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
fp = fopen("sample.txt", "r");
if (fp == NULL) {
perror("Unable to open the file\n");
exit(1);
}
char buf[256];
while (fgets(buf, sizeof(buf), fp) != NULL) {
printf("%s\n", buf);
print("~~~~\n");
}
fclose(fp);
return 0;
}
Output I got:(The entire file with the separator ~~~~ below each line)
Hi this is Stefen
~~~~
Hi How are you
~~~~
Can anyone please tell me how to do this?
As pmg suggests, would you please try the following:
#include <stdio.h>
#include <stdlib.h>
#define INFILE "sample.txt"
int main()
{
FILE *fp;
char buf[BUFSIZ];
int count = 0, n;
fp = fopen(INFILE, "r");
if (fp == NULL) {
perror(INFILE);
exit(1);
}
printf("Enter the line number: ");
fgets(buf, sizeof buf, stdin);
n = (int)strtol(buf, (char **)NULL, 10);
while (fgets(buf, sizeof buf , fp) != NULL){
if (++count == n) {
printf("%s", buf);
break;
}
}
fclose(fp);
return EXIT_SUCCESS;
}
Best to use a second file
check if you're at \n that means new line and increment a variable like "line"
printf(" \n Enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
ptr2 = fopen("c:\\CTEMP\\newfile.txt", "w");
if(ptr2==NULL)
printf("second error opening newfile");
while (!feof(ptr1))
{
ch = fgetc(ptr1);
if (ch == '\n')
{
temp++;
}
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file newfile.c
fputc(ch, ptr2);
}
}
fclose(ptr1);
fclose(ptr2);
"detele_line" variable is for the user to inter.
The easiest way is using array to save the lines, then print the certain line.
#include <stdio.h>
#define M 10010
#define N 256
char buf[M][N];
int main(){
FILE *file;
char fileName[50] = "sample.txt";
file = fopen(fileName, "r");
if(file == NULL)
return 1;
int n = 0;
while(fgets(buf[n], N, file) != NULL){
n++;
}
fclose(file);
int i, x;
printf("Example input:\nEnter the line number:");
scanf("%d", &x);
printf("Expected Output:\n%s", buf[x-1]);
return 0;
}

Write a program that reads the contents of a text file and writes the number of words, upper/lowercase letters and digits into a separate file

The report file should contain the following:
1. Number of words
2. Number of uppercase letters
3. Number of lowercase letters
4. Number of digits
I have successfully read the file and counted the words letters and digits but i am having issues with writing the contents to the new file, any help would be appreciated.
#include <stdio.h>
#include <ctype.h>
#define SIZE 40
int main(void)
{
char ch, filename[SIZE];
int digits = 0;
int upper = 0;
int lower = 0;
int entered = 0;
int words = 0;
unsigned long count = 0;
FILE *fp;
printf("Please enter the filename to read: ");
gets(filename);
// "r" reads the file fopen opens the file
if ((fp = fopen(filename, "r")) == NULL)
{
printf("Cannot open the file, %s\n", filename);
}
else
{
puts("Successfully opened, now reading.\n");
while ((ch=getc(fp)) != EOF)
{
if (isalnum(ch))
{
if(!entered)
{
entered = 1;
words++;
}
}
else
{
if (entered)
{
entered = 0;
}
}
if (isupper(ch))
{
upper++;
}
else if (islower(ch))
{
lower++;
}
else if (isdigit(ch))
{
digits++;
}
}
}
fclose(fp); //make sure to close the file if you open one
char filename2 [SIZE];
FILE *fp2;
fprintf(stdout, "Please enter the file name to write in: ");
gets(filename2);
if ((fp2 = fopen("filename2", "w")) == NULL)
{
printf("Cannot create the file, %s\n", filename2);
}
else
{
fprintf(fp2, "The file \"%s\" has %lu Words.\n", filename, words);
fprintf(fp2, "The file \"%s\" has %lu Digits.\n", filename, digits);
fprintf(fp2, "The file \"%s\" has %lu upper case letters.\n", filename, upper);
fprintf(fp2, "The file \"%s\" has %lu lower case letters.\n", filename, lower);
}
fclose(fp2);
return 0;
}
Instead of
if ((fp2 = fopen("filename2", "w")) == NULL)
write
if ((fp2 = fopen(filename2, "w")) == NULL)
Then, kick yourself.

Reading from two .txt file using fscanf in C, storing in structs and outputitng in .txt file

Description: program read data from 2 files, store them in structs,ask user for (city or place of residence), if city name matches with that stored in file, program displays output(student, national_ID,name) and store in a file.
My question is that, the above code that i wrote does not work. it gives me a "no information" even when i enter a city which is on the file.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LEN 20
#define MAX_LINE 7
typedef struct studentdata
{
char NATIONAL_ID[20];
char NAME[20];
char STUDENT_CODE[20];
char CITY[20];
}studentdata;
int main(void)
{
int i;
char x=0, CITY[MAX_LEN];
studentdata y[MAX_LINE];
char temp[20];
char temp1[20];
char count=0;
FILE *fi = fopen("employee1.txt", "r");
if (fi == NULL)
{
printf("error data");
exit(0);
}
FILE *fp = fopen("student1.txt", "r");
if (fp == NULL)
{
printf("error data1");
exit(1);
}
i = 0;
printf("Enter city\n");
scanf("%s",CITY);
//i = 0;
FILE *fa = fopen("student2.txt", "w");
if (fa == NULL)
{
printf("error data2");
exit(2);
}
while(fscanf(fi, "%s %s %s", y[i].NATIONAL_ID, y[i].NAME, y[i].STUDENT_CODE) == 4)
i++;
count=i;
I am sure the error is within this loop but can't just find it.
while(fscanf(fp, "%s %s", temp,temp1) == 2)
{
for(i=0; i< count;i++)
{
if (strcmp(y[i].NATIONAL_ID,temp)==0)
{
strcpy(y[i].CITY,temp1);
if (strcmp(y[i].CITY,CITY)==0)
{
fprintf( "%s\t %s\t %s\t %s\t\n", y[i].NATIONAL_ID, y[i].NAME, y[i].STUDENT_CODE, y[i].CITY);
x++;
}
}
}
}
fclose(fa);
if(!x)
{
printf("no information\n");
}
fclose(fi);
fclose(fp);
return 0;
}
I would say that nothing is being read from file into the in first while loop -
while(fscanf(fi, "%s %s %s", y[i].NATIONAL_ID, y[i].NAME, y[i].STUDENT_CODE) == 4)
i++;
As you match for 3 arguments but checks fscanf's return against 4 which will be false and loop will not iterate and i remains 0 , so as count.
Therefore , your this inner loop won't run-
for(i=0; i< count;i++) //count=0
and thus you don't get your output .
Modify your loop to -
while (fscanf(fi, "%s %s %s", y[i].NATIONAL_ID, y[i].NAME, y[i].STUDENT_CODE) ==3)
/* see fscanf's return is checked against 3 */
i++;
Note that an easy way to spot this problem would be to print the information as it is read, or print the array after the read is complete.

How to see if the first character of an inputfile is a number? C programming

void main()
{
FILE *fp1;
char ch;
int count = 0;
fp1 = fopen("Text.txt","r");
if(fp1==NULL){
printf("Failed to open file. Bye\n");
exit(1);
}
printf("Text file exists");
fclose(fp1);
}
example of an input file(Text.txt)-
3
nameA
nameB
nameC
I would like to check if the very first character of this input file is a number. If its missing a number than program will stop
Include ctype.h and then there are functions that do type checks. Alternatively check if the value of the char is in the appropriate ASCII range.
This would solve your problem
void main()
{
FILE *fp1;
char ch;
int count = 0;
fp1 = fopen("Text.txt","r");
if(fp1==NULL){
printf("Failed to open file. Bye\n");
exit(1);
}
printf("Text file exists");
ch = fgetc(fp1);
if (ch < '0' || ch > '9') {
fclose(fp1);
printf("Exit: First character is not a number\n");
return; // first character of the input file is not number so exit
}
fclose(fp1);
}
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *fp1;
char ch, line[128];
int count = 0, num;
fp1 = fopen("Text.txt","r");
if(fp1==NULL){
printf("Failed to open file. Bye\n");
exit(1);
}
printf("Text file exists\n");
if(fgets(line, sizeof(line), fp1)){
if(1==sscanf(line, "%d", &num)){
while(num-- && fgets(line, sizeof(line), fp1)){
printf("%s", line);
}
} else {
printf("The beginning of the file is not numeric. Bye\n");
exit(1);
}
} else {
printf("No contents of the file. Bye\n");
exit(1);
}
fclose(fp1);
return 0;
}

Search for keyword in textual file C

I'm having trouble reading a keyword from file that a user inputs to search for. The first part of the program asks for user input for naming the file. It then asks for sentence input. You can input sentences until you write "END". When you write "END", the appending of sentences to file should stop and the program should ask you for a keyword to search the sentences appended to the newly created textual file. I used 'gets' to ask for a word that will be searched for in the file. The program should find that word in a sentence and print back the whole sentence containing the keyword. The whole code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char fileName[128];
printf("Input your filename (end with .txt):");
gets(fileName);
FILE *filePointer = NULL;
char text1[128];
char word1[128];
filePointer = fopen(fileName, "a");
if(filePointer == NULL)
{
printf("Cannot open file!");
exit(EXIT_FAILURE);
}
else{
printf("Input your sentence: ");
while (fgets(text1, 127, stdin) != NULL && strncmp(text1, "END\n", 5) != 0){
printf("Input your sentence: ");
fprintf(filePointer, "%s", text1);
}
int line_num = 1;
int find_result = 0;
char text2[128];
filePointer = fopen(fileName, "r");
printf("Input keyword you're looking for: ");
gets(word1);
while(fgets(text2, 127, filePointer) != NULL) {
if((strstr(text2, word1)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", tekst2);
find_result++;
}
line_num++;
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
if(filePointer) {
fclose(filePointer);
}
return(0);
}
}
It all works, but the problem is somewhere here:
int line_num = 1;
int find_result = 0;
char text2[128];
filePointer = fopen(fileName, "r");
printf("Input keyword you're looking for: ");
gets(word1);
while(fgets(text2, 127, filePointer) != NULL) {
if((strstr(text2, rijec)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", text2);
find_result++;
}
line_num++;
}
I'm new at C programming, so I'm not sure where the flaw is. I know it should work in theory. It doesn't return a result when it clearly should.
You need to fclose() the file after writing, before reopening to read.
if (fclose(filePointer) != 0)
{
fputs("The sky is falling.", stderr);
return 1;
}
filePointer = fopen(fileName, "r");

Resources