Const number of words in a text - c

I tried to write a program for counting number of words in a text that taken from a file. I have a problem, the compiler can not find my file however I put this file in project folder.
what can I do?
#include <stdio.h>
#include <conio.h>
#include <string.h>
int words(const char sentence[ ]);
int main(void) {
char sentence[100];
FILE *cfPtr;
if ( (cfPtr = fopen("C programming.dat", "r")) == NULL ) {
printf( "File could not be opened\n" );
}
else {
fscanf(cfPtr, "%s", sentence);
}
words(sentence);
printf("%d", words(sentence));
getch();
return 0;
}
int words(const char sentence[ ]) {
int i, length = 0, count = 0, last = 0;
length = strlen(sentence);
for (i = 0; i < length; i++)
if (sentence[i] == ' ' || sentence[i] == '\t' || sentence[i] == '\n')
count++;
return count;
}

I'll try to improve usability of your program, accepting a filename as optional parameter
int main(ant argc, char *argv[]) {
char sentence[100];
const char *filename = "C programming.dat";
FILE *cfPtr;
if (argc == 2)
filename = argv[1];
if ( (cfPtr = fopen(filename, "r")) == NULL ) {
printf( "File '%s' could not be opened\n", filename );
}
else {
int total = 0;
while (fgets(sentence, sizeof sentence, cfPtr))
total += words(sentence);
printf("%d", total);
fclose(cfPtr);
}
getch();
return 0;
}
...
note: untested

If the file is not in the working directory (the folder your program is in) you need to specify the entire file path. On a Linux machine this would be something like "/home/your-user-name/Desktop/text.txt". For a Windows machine it would be "c:\\your\\file\path\\text.txt". If the file is in your working directory and the program still cannot find it, then it probably doesn't like the white space in the file name. Try naming it CProgramming.dat and see if that works.

Related

How to shuffle 2 different text file into 1?

#include <stdio.h>
int main(){
char temp[64];
FILE *fp1=fopen("data/1.txt","a");
FILE *fp2=fopen("data/2.txt","r");
while(fgets(temp,64,fp2)!=NULL){
fputs(temp,fp1);
}
fclose(fp1);
fclose(fp2);
return 0;
}
With such code I was able to combine 2 different text file into 1.
data/1.txt contents: abcdefghijk
data/2.txt contents: ABCDE
Outcome: abcdefghijkABCDE
However, I am struggling with shuffling 2 different text file.
Wanted result: aAbBcCdDeEfghijk
Followings are my current code.
#include <stdio.h>
#include <string.h>
int main(){
FILE *fp1,*fp2,*fp_out;
char ch1,ch2;
int result=1;
fp1=fopen("data/1.txt","r");
fp2=fopen("data/2.txt","r");
fp_out=fopen("data/out.txt","w");
//shuffling code area//
fclose(fp1);
fclose(fp2);
fclose(fp_out);
char buf[64]={};
fp_out=fopen("data/out.txt","r");
fgets(buf,64,fp_out);
if(!strncmp("aAbBcCdDeEfghijk",buf,64))
printf("PASS\n");
else
printf("FAIL\n");
fclose(fp_out);
return 0;
}
How can I design a code in "shuffling code area" in order to have outcomes like wanted result? I have thought about making 2 different FOR loops and combining but it kept showed an error.
This is some dirty way to do the job.
You can read the file which ever you want to write first character first and then read a character from second file and write both into third file one after the other.
Just adding extra code as per your need.
This just works for your case , not tested with many cases and corner cases.
#include <stdio.h>
#include <string.h>
int main(){
FILE *fp1,*fp2,*fp_out;
char ch1,ch2;
int result=1;
int file1_content_over = 0;
int file2_content_over = 0;
fp1 = fopen("data/1.txt","r");
fp2 = fopen("data/2.txt","r");
fp_out=fopen("data/out.txt","w");
//shuffling code area//
// read till file1_content_over or file2_content_over is not finished
while(! file1_content_over || !file2_content_over)
{
ch1 = fgetc(fp1);
ch2 = fgetc(fp2);
if(ch1 != EOF)
fputc(ch1,fp_out);
else
file1_content_over = 1;
if(ch2 != EOF)
fputc(ch2,fp_out);
else
file2_content_over = 1;
}
//shuffling code area//
fclose(fp1);
fclose(fp2);
fclose(fp_out);
char buf[64]={};
fp_out=fopen("data/out.txt","r");
fgets(buf,64,fp_out);
printf("buf = %s\n", buf);
if(!strncmp("aAbBcCdDeEfghijk",buf,strlen("aAbBcCdDeEfghijk")))
printf("PASS\n");
else
printf("FAIL\n");
fclose(fp_out);
return 0;
}
Working for me! Not the best optimized code, I didnt get to much time to that!
Main():
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
int removingSPaces(char array[MAX], int sizeArray);
void orderChar(char bufFile1[MAX], char bufFile2[MAX], char bufOut[MAX], int maxSize, int sizeBuf1, int sizeBuf2);
int getChar(char buf[MAX], FILE *fp);
int main(){
FILE *fp1, *fp2, *fpOut;
char bufFile1[MAX] = {0}, bufFile2[MAX] = {0}, bufOut[MAX] = {0};
int sizeBuf1 = 0, sizeBuf2 = 0;
int maxSize=0;
if((fp1=fopen("file1.txt","r")) == NULL || (fp2=fopen("file2.txt","r")) == NULL || (fpOut=fopen("fileOut.txt","w")) == NULL){
perror("");
exit(1);
}
sizeBuf1 = getChar(bufFile1, fp1); //geting the chars from file1
fclose(fp1);
sizeBuf1 = removingSPaces(bufFile1, sizeBuf1); //removing the \n if exists from chars of file1
sizeBuf2 = getChar(bufFile2, fp2); //geting the chars from file2
fclose(fp2);
sizeBuf2 = removingSPaces(bufFile2, sizeBuf2); //removing the \n if exists from chars of file2
maxSize = sizeBuf1 + sizeBuf2; //Max Size to loop for
orderChar(bufFile1, bufFile2, bufOut, maxSize, sizeBuf1, sizeBuf2); //Order the chars!
fprintf(fpOut, "%s", bufOut); //Printing to the file
fclose(fpOut);
/* COPIED FROM YOUR CODE */
char buf[64]={0}; //Just added the 0, because you cant initialize the array like with only {}
if((fpOut=fopen("fileOut.txt", "r")) == NULL){
perror("");
exit(1);
}
fgets(buf,64, fpOut);
if(!strncmp("aAbBcCdDeEfghijk", buf, 64))
printf("PASS\n");
else
printf("FAIL\n");
fclose(fpOut);
/* COPIED FROM YOUR CODE */
return 0;
}
Functions():
int removingSPaces(char array[MAX], int sizeArray){
int size = sizeArray;
if(array[sizeArray -1] == '\n'){
array[sizeArray -1] = '\0';
size = strlen(array);
}
return size;
}
int getChar(char buf[MAX], FILE *fp){
char bufAux[MAX];
int size;
while(fgets(bufAux, sizeof(bufAux), fp)){
size = strlen(bufAux);
}
strcpy(buf, bufAux);
return size;
}
void orderChar(char bufFile1[MAX], char bufFile2[MAX], char bufOut[MAX], int maxSize, int sizeBuf1, int sizeBuf2){
int positionsF1=0, positionsF2=0;
int aux = 0; //This will starts organization by the first file! If you want to change it just change to 1;
for(int i=0; i < maxSize; i++){
if(aux == 0 && positionsF1 != sizeBuf1){
bufOut[i]=bufFile1[positionsF1];
if(positionsF2!=sizeBuf2){
aux = 1;
}
positionsF1++;
}else if(aux == 1 && positionsF2 != sizeBuf2){
bufOut[i]=bufFile2[positionsF2];
if(positionsF1!=sizeBuf1){
aux = 0;
}
positionsF2++;
}
}
}
Content of file 1:
abcdefghijk
Content of file 2:
ABCDE

How to split a text file into multiple parts in c

What i need to do, is to take a file of n lines, and for every x lines, create a new file with the lines of the original file. An example would be this:
Original File:
stefano
angela
giuseppe
lucrezia
In this case, if x == 2, 3 file would be created, in order:
First file:
stefano
angela
Second FIle:
giuseppe
lucrezia
Third File:
lorenzo
What i've done so far is this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
int getlines(FILE *fp)
{
int c = 0;
int ch;
do{
ch = fgetc(fp);
if(ch == '\n')
{
c++;
}
}while(ch != EOF);
fseek(fp, 0 , SEEK_SET);
return c;
}
int ix = 0;
void Split(FILE *fp, FILE **fpo, int step, int lines, int *mem)
{
FILE **fpo2 = NULL;
char * filename = malloc(sizeof(char)*64);
char * ext = ".txt";
char number[2];
for(int i = ix; i < *mem; i++)
{
itoa(i+1, number,10);
strcpy(filename, "temp");
strcat(filename, number);
strcat(filename, ext);
if(!(fpo[i] = fopen(filename, "w")))
{
fprintf(stderr, "Error in writing\n");
exit(EXIT_FAILURE);
}
}
char ch;
int c = 0;
do{
ch = fgetc(fp);
printf("%c", ch);
if(ch == '\n')
{
c++;
}
if(c >= step)
{
c = 0;
ix++;
if(ix >= *mem && (ix*step) <= lines)
{
*mem = *mem + 1;
fpo2 = realloc(fpo, sizeof(FILE*)*(*mem));
Split(fp, fpo2, step, lines, mem);
}
}
putc(ch, fpo[ix]);
}while(ch != EOF);
}
int main()
{
FILE * fp;
if(!(fp = fopen("file.txt", "r")))
{
fprintf(stderr, "Error in opening file\n");
exit(EXIT_FAILURE);
}
int mem = N;
int lines = getlines(fp);
int step = lines/N;
FILE **fpo = malloc(sizeof(FILE *)*N);
Split(fp, fpo, step, lines, &mem);
exit(EXIT_SUCCESS);
}
I'm stack with segmentation error, i couldn't find the bug doing
gdb myprogram
run
bt
I really appreciate any help.
EDIT:
I've changed some things and now it works, but it creates an additional file that contains strange characters. I need to still adjust some things:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
int getlines(FILE *fp)
{
int c = 0;
int ch;
do{
ch = fgetc(fp);
if(ch == '\n')
{
c++;
}
}while(ch != EOF);
fseek(fp, 0 , SEEK_SET);
return c;
}
int ix = 0;
void Split(FILE *fp, FILE **fpo, int step, int lines, int *mem)
{
FILE **fpo2 = NULL;
char * ext = ".txt";
for(int i = ix; i < *mem; i++)
{
char * filename = malloc(sizeof(char)*64);
char * number = malloc(sizeof(char)*64);
itoa(i+1, number,10);
strcpy(filename, "temp");
strcat(filename, number);
strcat(filename, ext);
if(!(fpo[i] = fopen(filename, "w")))
{
fprintf(stderr, "Error in writing\n");
exit(EXIT_FAILURE);
}
free(number);
free(filename);
}
char ch;
int c = 0;
do{
ch = fgetc(fp);
printf("%c", ch);
if(ch == '\n')
{
c++;
}
if(c >= step)
{
c = 0;
ix++;
if(ix >= *mem && ((ix-1)*step) <= lines)
{
*mem = *mem + 1;
fpo2 = realloc(fpo, sizeof(FILE*)*(*mem));
Split(fp, fpo2, step, lines, mem);
}
}
putc(ch, fpo[ix]);
}while(ch != EOF);
}
int main()
{
FILE * fp;
if(!(fp = fopen("file.txt", "r")))
{
fprintf(stderr, "Error in opening file\n");
exit(EXIT_FAILURE);
}
int mem = N;
int lines = getlines(fp);
int step = lines/N;
FILE **fpo = malloc(sizeof(FILE *)*N);
Split(fp, fpo, step, lines, &mem);
exit(EXIT_SUCCESS);
}
There are a few problems in your code. But first I think you need to fix the most important thing
int step = lines/N;
Here step is 0 if your input file has less than N lines of text. This is because lines and N both are integer and integer division is rounding down.
I won't fix your code, but I'll help you with it. Some changes I
suggest:
Instead of getlines, use getline(3) from the standard
library.
fseek(fp, 0 , SEEK_SET) is pointless.
In char * filename = malloc(sizeof(char)*64), note that
both arguments to malloc are constant, and the size is arbitrary.
These days, it's safe to allocate filename buffers statically,
either on the stack or with static: char filename[PATH_MAX].
You'll want to use limits.h to get that constant.
Similarly you have no need to dynamically allocate your FILE
pointers.
Instead of
itoa(i+1, number,10);
strcpy(filename, "temp");
strcat(filename, number);
strcat(filename, ext);
use sprintf(filename, "temp%d%s", i+1, ext)
get familiar with err(3) and friends, for your own convenience.
Finally, your recursive Split is -- how shall we say it? -- a nightmare. Your whole program
should be something like:
open input
while getline input
if nlines % N == 0
create output filename with 1 + n/N
open output
write output
nlines++

How to copy characters from an array to user created file in C

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char file_name[50], ch, text[140];
int i;
printf("Enter a file name to create :");
scanf("%s", file_name);
fp = fopen(file_name,"w");
if(fp == NULL)
{
printf("The file %s could not open !", file_name);
exit(EXIT_FAILURE);
}
printf("Enter some text into %s : (enter * to finish)\n", file_name);
while((ch=getchar()) != '*')
{
for(i=0;i<140;i++)
text[i] = ch;
}
for(i=0;i<140;i++)
{
fprintf(fp,"%c",text[i]);
}
fclose(fp);
printf("Your datas has been successfully copied into file %s",file_name);
return 0;
}
It creates the file but does not copies the content of the array to the user created file. So it just creates empty file. In which part I have mistake can anyone help to fix this problem ?
See the below code block, here for loop is unnecessary, outer while loop is enough.
while((ch=getchar()) != '*')
{
for(i=0;i<140;i++) /* 140 times same char you are copying into text */
text[i] = ch;
}
It should be
int i = 0;
while((ch=getchar()) != '*' && (i < 140)) { /* just one more condition so that it should exceeds 140 char */
text[i] = ch;
i++; /* when loop fail i is the count of no of char to be written to file */
}
And while putting data into file using fprintf()
for(index = 0;index < i ;index++) { /* i is the count */
fprintf(fp,"%c",text[index]);
}

Replace a word in a text file, then output the overwritten version

For this problem I'm asked to first read from the input text file, prompt the user which word/string to get replaced, then output the same file (the original gets overwritten). The thing is the input/outputfile name must always have a specific name for example test.txt (this is what bothers me)
Here's the function which I tested out and it does the job replacing, but for now I'm prompting user to enter their own "sentence" and then for words. I'm lost on how to (always) read from a test.txt and then output the same one with replaced string.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *w_replace(const char *s, const char *oldone, const char *newone)
{
char *ret;
int i, count = 0;
int newlen = strlen(newone);
int oldonelen = strlen(oldone);
for (i = 0; s[i] != '\0'; i++)
{
if (strstr(&s[i], oldone) == &s[i])
{
count++;
i += oldonelen - 1;
}
}
ret = (char *)malloc(i + count * (newlen - oldonelen));
if (ret == NULL)
exit(EXIT_FAILURE);
i = 0;
while (*s)
{
if (strstr(s, oldone) == s) //compare
{
strcpy(&ret[i], newone);
i += newlen;
s += oldonelen;
}
else
ret[i++] = *s++;
}
ret[i] = '\0';
return ret;
}
int main(void)
{
char mystr[100], c[10], d[10];
char fileOld[32] = "test.txt";
char fileNew[32] = "test.txt";
char word_search[80];
char word_replace[80];
FILE *fp1, *fp2;
fp1 = fopen(fileOld,"r");
fp2 = fopen(fileNew,"w");
printf("Enter the word to replace :\n");
scanf(" %s",word_search);
printf("Enter the new word:\n");
scanf(" %s",word_replace);
char *newstr = NULL;
newstr = w_replace(fileOld, word_search , word_replace);
fputs(word_replace, fp2);
fclose(fp2);
fclose(fp1);
return 0;
}
So if a test.txt contains the following sentence
This is a test
Result
Enter the word to replace :
This
Enter the new word:
That
The new updated test.txt file will only be
That
instead of
That is a test
Needed values (using the var names you gave above):
#include <fcntl.h>
int file_descriptor;
int size_of_text = <whatever you want here>;
char *file_name = "test.txt";//or whatever
char newone[size_of_text];
char oldone[size_of_text];
To read from a file:
file_descriptor = open(file_name,O_RDONLY);//O_RDONLY opens for read only
read(file_descriptor,oldone,sizeof(oldone));//reads file into oldone
close(file_descriptor);//closes so you don't accidentally read or write to it later, and so you can use it again
To write to a file:
file_descriptor = open(file_name,O_WRONLY | O_TRUNC);//O_WRONLY opens for writing only, O_TRUNC will truncate the file if it exists
write(file_descriptor,newone,sizeof(newone);//writes newone to file
close(file_descriptor);
For more information on read(),write(),open(),close():
http://www.gdsw.at/languages/c/programming-bbrown/c_075.htm

How do I find a string in a file?

I'm new at C and recently finished my work with files. I tried to create a program which will find an entered name in a file but it does not work. Could you try to repair it? I'll be thankful.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fr;
int i,p,counter,final,length,j,c,k = 0;
char name[256];
char buffer[1024];
fr = fopen("C:/Users/prixi/Desktop/HESLA.TXT","r");
while ((c = fgetc(fr)) != EOF)
counter++;
printf("Enter the name");
scanf("%s",&name);
length = strlen(name);
while (fscanf(fr, " %1023[^\n]", buffer) != EOF) {
for (i = 0; i <= counter; i++)
if (name[0] == buffer[i]){
for (j = 0;j < length; j++ )
if (name[j] == buffer[i+j])
p++;
else
p = 0;
/* The 2nd condition is there because after every name there is ' '. */
if (p == length && buffer[i+j+1] == ' ')
final = 1;
}
}
if ( final == 1 )
printf("its there");
else
printf("its not there");
return 0;
}
It loads the inside of the file to the buffer and then scans char by char depending on how long the file is. I know that it's inefficient and slow, but I have been learning C only for like 4 days. I would really like you to help me fixing my own code otherwise :D I probably wont be able to fall asleep.
There are a lot of way to search a string into a File.
Try this:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *loadFile(const char *fileName);
int main (void) {
const char *fileName = "test.txt";
const char *stringToSearch = "Addams";
char *fileContent = loadFile(fileName);
if (strstr(fileContent, stringToSearch)){
printf("%s was Found\n",stringToSearch);
}else{
printf("%s was not Found\n",stringToSearch);
}
free(fileContent);
return 0;
}
char *loadFile(const char *fileName){
size_t length,size;
char *buffer;
FILE *file;
file = fopen (fileName , "r" );
if (file == NULL){
printf("Error fopen, please check the file\t%s\n",fileName);
exit(EXIT_FAILURE);
}
fseek (file , 0 , SEEK_END);
length = (size_t)ftell (file);
fseek (file , 0 , SEEK_SET);
buffer = malloc(length+1);
if (buffer == NULL){
fputs ("Memory error",stderr);
exit (2);
}
size = fread (buffer,1,length,file);
if (size != length){
fputs ("Reading error",stderr);
exit(3);
}
buffer[length] = '\0';
fclose (file);
return buffer;
}
Output:
Addams was Found
I have inside the file "test.txt" the following:
Michael Jackson
Bryan Addams
Jack Sparrow
There are multiple problems with your code. You did not post the variable definitions, so we cannot verify if they are used consistently, especially name that should be an array of char.
The main issue is this: you count the number of bytes in fr by reading it, but you do not rewind the stream before scanning it for instances of the string.

Resources